Skip to content

Installation

Gaël Métais edited this page Jul 29, 2016 · 4 revisions

You'll need to compile your own sw-delta.js service worker script, so that the library AND your configuration are both combine into a single JS file. This compilation is done with Browserify.

Prerequisites

  • NodeJS is installed on your system.
  • Your project is npm ready (it has a package.json file). Otherwise, you need to npm init your project.

Install browserify and sw-delta

Get to your project's root and write:

npm install browserify sw-delta --save-dev

Create your configuration file

Create a file called standalone-sw.js in your project's source code. This is the source file that will be compiled, so there's no need to make it accessible on the internet. Copy the following code inside:

var SwDelta = require('sw-delta');

var settings = {
    files: [
        '/assets/*.js',
        '/assets/*.css'
    ],
    removeCookies: true
};

var swDeltaInstance = new SwDelta(settings);

self.addEventListener('fetch', swDeltaInstance.onFetch);

self.addEventListener('activate', function () {
    console.log('[sw-delta service worker] Activated');
});

Adapt the settings to your needs

Change the settings object according to the API.

Add the compilation script to your package.json

Inside package.json, find the "scripts": { } object (create it if needed) and add this line:

"scripts": {
    "sw-delta-compile": "browserify -r ./<your path to>/standalone-sw.js:sw-delta --standalone worker > ./<destination path>/sw-delta.js"
}

Compile

Now (and after each modification) to your settings. Get to your project's root and write:

npm run sw-delta-compile

If everything went right, you should find your newly created file at ./<destination path>/sw-delta.js.

Call the service worker on your website

Define the service worker like this, anywhere on your page:

<script>
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/<the public path>/sw-delta.js');
    }
</script>

Note that the sw-delta.js should be placed at the root of your website or at least at the root of the files you want to be controlled by sw-delta.

Congratulations

The service worker is installed! You don't need to change anything else on your website.

Help improving this documentation

If you have any problem during the installation step, there's a high probability that someone else encounters the same problem. Please open a ticket even if you found the solution by yourself and I'll try to improve the documentation.