Asial Blog

Google Chrome Dev Summit. Let's take a look at Service Workers!

Category :
Frontend(HTML5)
Tags :
JavaScript
Last week we attended Google Chrome Dev Summit. It is a conference hosted at the Google campus in Mountain View, CA. It is an opportunity for the engineers working on Chrome to showcase new features as well as receive feedback from the developer community.



The conference was a nice experience. I met a lot of interesting people and had a lot of fun. Actually it was my first time going to America and I really liked it. We we're staying in an older area of San Francisco with beautiful Victorian houses. The area is also famous for its graffiti.



I also had the opportunity to eat some really good food while there.

Two things in focus this year was Google's new design spec called Material Design as well as the new Service Worker API. Polymer, a JavaScript library used to create custom web components, was also discussed extensively.

I thought the Service Worker API looked really interesting so I will focus on that in this article. It is a new way to cache web pages to make them runnable offline. It can be used to cache the assets as well as the application data. Basically, it can be used to install a web application on a desktop computer or onto a mobile device.

This in conjunction with adding the web site to the Home screen can, as one of the Google engineers put it, make web apps more "appy". For native apps, being able to reach them directly from the home screen as well as running them offline is expected. Web apps, even if they really don't need an internet connection, often require one since the assets need to be downloaded.

Can I use Service Workers?


Actually, the API is still work in progress and isn't supported in any stable browser version yet. However, It's possible to play around with the API using the Firefox Nightly build as well as in Chrome Canary. Please see this page on how to activate service workers for your browser.

It actually didn't run very well in the latest version of Chrome Canary so I've been using the Firefox Nightly build while writing this article.

The API will be available in Chrome 41 which will be released early next year. This page shows the current state of implementation in all the major browsers.

How to create a Service Worker


The API is quite simple and using feature detection it can safely be added to an existing web application even though most browsers still don't support it.

  1. if ('serviceWorker' in navigator) {
  2.   navigator.serviceWorker.register('/my-app/sw.js', {
  3.     scope: '/'
  4.   }).then(function() {
  5.     console.log('Registration succeeded.');
  6.   }).catch(function(error) {
  7.     console.log('Registration failed with ' + error);
  8.   });
  9. };

First we check if the Service Worker API is available. Then the navigator.serviceWorker.register() method is called to register the Service Worker. This method returns a promise. The first argument is a JavaScript file that will be downloaded and executed.

Using the Service Worker to cache assets


After the Service Worker has been registered an 'install' event will be triggered. So in sw.js we can listen for this event.

  1. // sw.js
  2. this.addEventListener('install', function(event) {
  3.   event.waitUntil(
  4.    caches.create('v1').then(function(cache) {
  5.          return cache.add(
  6.         '/my-app/',
  7.         '/my-app/index.html',
  8.         '/my-app/style.css',
  9.         '/my-app/app.js',
  10.         '/my-app/logo.jpg',
  11.         ... // other assets that we might want to cache.
  12.      );
  13.    })
  14.    );
  15. });


  • The caches.create(name) method will return a promise which resolves when the cache is created. The cache is named so when updating the application we can use a new version of the cache as well.

  • Assets are added to the cache using cache.add()


Using the cache


Now we've created a cache and populated it with all our assets. So how do we tell the browser to use our cache instead of doing a regular request to request the assets?

The Service Worker API also triggers a 'fetch' event when a resource is requested. The simplest way to use the caching is just to return the assets from the cache if they're present:

  1. // sw.js
  2. this.addEventListener('fetch', function(event) {
  3.   event.respondWith(
  4.     // this will respond with what is in the cache.
  5.     caches.match(event.request);
  6.   );
  7. });

The caches.match() method returns a Promise that can be used to handle exceptions. In the following example the resource will be fetched with a regular request if it's not present in the cache.

  1. // sw.js
  2. this.addEventListener('fetch', function(event) {
  3.   event.respondWith(
  4.     caches.match(event.request).catch(function() {
  5.       return event.default();
  6.     });
  7.   );
  8. });

It is possible to add resources dynamically to the cache as well. We can build up the cache gradually and save resources for when the application runs in offline mode. It's also possible to add resources from cross-site requests so we can even cache remote assets like content from a CDN.

Please see this page for more usage examples.

I think this is a nice API that's easy to use and gives us the ability to run web apps offline. As more and more native features become available we will be able to make more and more native-feeling apps running directly in the browser.