简体   繁体   English

刷新在服务工作者中使用importScripts导入的脚本

[英]Refresh scripts imported with importScripts in service worker

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). 假设使用一些新代码更新了script.js ,并且由于推送事件而激活了服务工作者(用户同时没有再访问过我的网站)。

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? 每次激活服务工作者时, importScripts检查更新吗?或者在首次安装服务工作者时,它只下载一次script.js吗?

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. Service Workers规范中 ,通过importScripts导入的脚本在安装/更新Service Worker时存储在映射中,然后重新使用,直到进行新的更新。 There's a discussion on GitHub with more details. 有关更多细节的讨论GitHub

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. 可以通过动态生成服务工作者URL来强制浏览器重新验证/检查通过importScripts()包含的代码是否已更新 - 如果每小时更改一次,则浏览器将下载并安装“新”服务工作者,包括所有导入的脚本。

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; 演示 - 打开JS控制台并单击; you should see the imported script reloaded every 10 seconds. 你应该看到导入的脚本每10秒重新加载一次。

(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.) (这并不能完全解决您的问题(服务工作者仅在用户访问页面时更新,而不是在收到推送通知时更新),但这可能就足够了。)

From chrome 68, this can be done by setting {updateViaCache: 'none'} while registering service worker. 从chrome 68开始,这可以通过在注册服务工作者时设置{updateViaCache: 'none'}来完成。 It doesn't use cache then for contents of imported files 然后它不使用缓存来导入文件的内容

See full reference about definition at w3 and Chrome Updates 请参阅有关w3Chrome更新的定义的完整参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM