Configuration

The Service Worker is a Javascript file you can declare in the configuration file. It will be automatically served by the bundle as long as your template file uses the Twig pwa method.

/config/packages/pwa.yaml
pwa:
    serviceworker: "sw.js"

"sw.js" is served by Asset Mapper and refers to the file in /assets/sw.js folder of your project. It can be stored elsewhere if needed.

To start, just put an empty file. It will be automatically populated by the bundle and will evolves depending on your application needs.

The following example is exactly the same:

/config/packages/pwa.yaml
pwa:
    serviceworker:
        enabled: true
        src: "sw.js"

As it has an impact on the Twig pages, you may need to clear the cache when the service worker is enabled.

By default, the public URL of the service worker will be /sw.js. You can change this URL using the dest configuration option.

/config/packages/pwa.yaml
pwa:
    serviceworker:
        enabled: true
        src: "sw.js"
        dest: "/foo/service-worker.js"

Service Worker Initialization

The Service Worker initialization script uses either Workbox Window if enabled or a smiliar Vanilla JS script.

When Workbox is enabled, its initialization script typically loads from an external URL. However, for improved performance and security, we advise installing it via Asset Mapper instead of relying on remote loading.

Other Options

The Service worker section has other options you may be interested in.

Scope

The scope parameter defaults to /. It is a string representing the service worker's registration scope. It should be aligned with the Manifest scope.

Cache

The use_cache parameter is enable by default. It is a boolean that sets how the HTTP cache is used for service worker script resources during updates.

Skip Waiting

The skip_waiting parameter is disabled by default. It ensures that any new versions of a service worker will take over the page and become activated immediately. It is safe in general, but may create issues when the old service worker is handling events while it is updated.

/config/packages/pwa.yaml
pwa:
    serviceworker:
        enabled: true
        src: "sw.js"
        dest: "/foo/service-worker.js"
        scope: "/"
        use_cache: true
        skip_waiting: false

Last updated