A service worker is optional, but recommended service used in the New Experiments and Browser push notifications that work to guarantee a successful server response when loading a webpage containing Exponea modifications. Service workers can act as proxy servers that sit between web applications, the browser, and the network. If the load request doesn’t respond (because of an error or a server outage) until the predefined timeout, the request is cut off. This way, for example, experiments will not get applied, but the page load is not blocked.
To set up a service worker, you must create a file called “service-worker.js” in your webroot directory. There can only be one service worker for a single domain, therefore:
- If your domain does not have a service worker file, create a new one with the content below and upload the file "service-worker.js" to your webroot directory.
- If your domain already has a service worker file, append the content below to the end of your existing file.
To load the Exponea service worker, insert the following code into your "service-worker.js":
Once you have done that, you can test if the new script is available on the root of your domain, by visiting: https://YOUR-DOMAIN.com/service-worker.js (change YOUR-DOMAIN to your web address).
To ensure that the service worker is not cached forever, make sure that your service-worker.js is served with a header
cache-control: max-age=0, or if you use and register the Service Worker within your own scripts, set
updateViaCache to imports/none. This will ensure that the visitors will have the latest service worker all the time.
The service worker will not work with the first load of the webpage, during which it will be registered. When using the New Experiments, the webpage will fallback to CSS Hiding during the first load.
The script service-worker.js cannot be run in Google Tag Manager. This file contains the definition of Service Worker and must be first registered to enable its functionality.
In terms of security, the service worker file must be hosted on HTTPS on the same domain, which means that service workers and their service worker clients cannot be hosted on CDNs. Read more here.
Updated about a month ago