I have a website which has a service worker like:
// Import a script from another domain
importScripts('.js')
Suppose that script.js
is updated with some new code and the service worker is activated due to a push event (the user is the meantime has not visited my website again).
Does importScripts
checks for updates each time the service worker is activated or it downloads the script.js
just once when the service worker is first installed?
Is there any way to have the service worker code (and in particular the imported scripts) refreshed each time the service worker receives a push message?
I have a website which has a service worker like:
// Import a script from another domain
importScripts('https://example./script.js')
Suppose that script.js
is updated with some new code and the service worker is activated due to a push event (the user is the meantime has not visited my website again).
Does importScripts
checks for updates each time the service worker is activated or it downloads the script.js
just once when the service worker is first installed?
Is there any way to have the service worker code (and in particular the imported scripts) refreshed each time the service worker receives a push message?
Share Improve this question asked Jun 30, 2016 at 10:10 collimarcocollimarco 35.5k37 gold badges115 silver badges155 bronze badges 1- I wrote a blog post with some tips. – collimarco Commented May 1, 2017 at 14:07
3 Answers
Reset to default 5From the Service Workers specification, scripts imported via importScripts
are stored in a map when the Service Worker is installed/updated and are then reused until a new update. There's a discussion on GitHub with more details.
I can't think of a way to reload the imported scripts when a service worker receives a push message. What is your use case?
It's possible to force the browser to revalidate/check whether code included via importScripts()
has been updated by dynamically generating the service worker URL—if this changes every hour, then the browser will download and install a "new" service worker, including all imported scripts.
The following code will cause the browser to check all dependencies every hour:
const MAXAGE = 3600; // seconds until recheck
const URL = `/sw.js?q=${Math.floor(Date.now() / (MAXAGE * 1000))}`;
navigator.serviceWorker.register(URL);
Demo — open JS console and click around; you should see the imported script reloaded every 10 seconds.
(This doesn't pletely solve your problem (the service worker is only updated when the user visits the page, not when the push notification is received) but it might be sufficient.)
From chrome 68, this can be done by setting {updateViaCache: 'none'}
while registering service worker. It doesn't use cache then for contents of imported files
See full reference about definition at w3 and Chrome Updates