Refresh scripts imported with importScripts in service worker
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.)