Short Bytes:Did you know that with the advent ofService Workers, one could start making websites work offline! Such web apps are called PWAs (Progressive Web Apps). In this how-to, I’m going to help you out to use a service worker to make aJekyll-based blog/website work offline and some cool things that come with it.

(NOTE:The snippets of code in the article are taken from my blog’scode repository. It can be referred if needed. If you are new to Jekyll, you could read3 Series Article on CSS Tricks.)

jekyll blog

BACKGROUND

Earlier there used to be a yuk YAML file based App Cache, which was very hard coded in nature and couldn’t be used to cache assets and web pages dynamically. Enter, Service Workers. Simple plain event based Javascript API to do dynamic service worker caching to store assets, so that they could be used to serve the web pages when there’s no network.

Service workers landed inChrome Canaryin 2014, but its spec is still being revised/added upon and designed. In 2015 and 2016, Google’s Chrome team spread the word out heavily of this new technology in the browsers. Only Applehas not supported this(even at the time of writing this article) on their devices (for unknown reasons) [They also aren’t actively participating in any spec discussions about service workers too].

Screenshot_20170123-232947

What is a service worker? Basically, it is aweb workeron steroids. One characteristic of a web worker is that all the tasks of a web worker run separately (asynchronously) from the main JavaScript execution thread (event loop). This feature helps run CPU or memory intensive tasks, for example, complicated calculations without compromising the performance of your User Interface of the web app.

Service Worker lets us cache (store for a long time) assets, such as JavaScript, CSS, HTML, image, font files in the service worker cache of the browser, so the next time the user loads that page, it is loaded almost instantly. And also since in this caching strategy, the browser looks for the availability of the assets first from service worker cache, the web page is served even when one is offline! If any asset is not there in the cache, then a network request is sent to fetch it.

Service worker also enables the push notifications that are common to see on many websites these days including Facebook, Whatsapp on web and Twitter. We’ll primarily be talking about the offline feature. This how-to is specific to Jekyll, however, most of the service worker code can be generally applied to any website.

Since Jekyll serves static contents (it’s a static site generator, duh!), our service worker code would be very basic and easy to understand.

LET’S ROLL:

On all the relevant pages, the following piece of script gets executed. It’s doing following things:

You can add this piece of code in a file sayserviceWorker.htmlinside theincludesdirectory of your Jekyll code and include it indefault.htmlusing Jekyll’s liquid templating engine

Now to the actual service worker code that does the magic. This code resides insw.jsat your Jekyll Code’s Root.

staticCacheNameis the cache version which is to be updated every time I make some changes to the cached responses (for example I make a change in say a CSS file or a blog post). And, I’m just defining what requests I want to intercept and cache in an array (used in the next snippet).

self.skipWaiting, is to say, that every time thissw.jsfile changes, the newer version of the service worker shouldn’t be queued, but made active immediately (One could ask for user prompt to refresh the page giving a message likeWebpage has been updated/changed, click Refresh to load new posts or whatever.), throwing away the older version.

e.waitUntilquoting from MDN website:

“TheExtendableEvent.waitUntil()method extends the lifetime of the event. In service workers, extending the life of an event prevents the browser from terminating the service worker before asynchronous operations within the event have completed.”

I open up a cache namedgdad-s-river-static-v61, which returns a promise with my cache name, and then I callcache.addAll(which uses thefetch APIin the background), which fetches all the requests in the array provided and caches them.

On to the next snippet!

When service worker activates, I’m ensuring that, any service worker which is not the latest version gets deleted. For example, if my latest cache version is saygdad-s-river-static-v61, and someone is still ongdad-s-river-static-v58, on his/her next visit, I want that client to not care about pumping one version at a time, but forthrightly delete that version to install the latest one.

In the fetch event, I’m simply telling the service worker, how to respond to a particular request made (since we are hijacking the response giving power, service workers only work on secure aka https origin websites). I tell it to match the request to those cached in the browser, and if it doesn’t find that particular response to the request, fetch it through the network, else serve it from the cache.

Tada! Service worker made Jekyll powered blog offline!

SURPRISE! THE COOL THING:

Bummer:This wouldn’t work on iOS devices.

If you add a web appmanifest.jsonfile at your root of the project like this:

and add it in thehead.htmlfile inside the head tag,

Then, on thesecond visit of your website (within 5 minutes), will prompt the user to add your website to your home screen (to reside with an icon, just like other native apps), which you’ll be engaged with just like an app.

Did you find this article on Jekyll Blog interesting and helpful? Don’t forget to share your views and feedback.

Also Read:Ecosia — The Search Engine That Plants Trees