sw-lightning-talk



sw-lightning-talk

0 0


sw-lightning-talk

Slides for a lightining talk about Service Workers.

On Github herschel666 / sw-lightning-talk

Service Worker

Defining cache version & relevant files

                        
var APP_VERSION = 'v-dhth-<version>';
var urlsToCache = [
    '/',
    '/main.js',
    '…'
];
                        
                    

Installing the Service Worker & caching the files

                        
self.addEventListener('install', function (evnt) {
    evnt.waitUntil(caches.open(APP_VERSION).then(
        function (cache) {
            cache.addAll(urlsToCache);
        }, console.error)
    );
});
                        
                    

Handling requests

                        
self.addEventListener('fetch', function (evnt) {
    evnt.respondWith(caches.match(evnt.request).then(function (response) {
        return response || fetch(evnt.request);
    }));
});
                        
                    

This all happens in the service-worker.js, which is included like this:

                        
if ( 'serviceWorker' in navigator ) {
    navigator
        .serviceWorker
        .register('/service-worker.js')
        .then(function () {}, console.error);
}
                        
                    

That's all?

Almost …

There are two requirements.

  • A modern Browser … #youdontsay
  • The webapp has to be served via https

Links

Thx!

Service Worker