I have a website which has a service worker like:
// Import a script from another domain
importScripts('https://example.com/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?
From 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 completely 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With