您好,我在 express 上有一个生成 HTML 的 ejs 模板。我在这个模板中写了我的 service worker 注册码,这个模板对网站的所有页面都是通用的,因此,注册码最终出现在网站的每个页面上。因此,在每次用户访问时,都会运行 service worker 注册代码,我认为这是不好的。如何让这段代码只在用户第一次访问时运行?
请在下面找到我的代码:
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
var hashes = {};
["appCss", "appJs"].map((val,idx) => {
let prop;
if(document.getElementById(val)) {
prop = val.toLowerCase().indexOf("css") == -1 ? "src" : "href";
hashes[val] = document.getElementById(val)[prop];
}
});
hashes = JSON.stringify(hashes);
navigator.serviceWorker
.register(`/service-worker.js?hash=${encodeURIComponent(hashes)}`)
.then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
console.log('ServiceWorker registration failed:', err);
});
});
}
</script>
最佳答案
The register() method of the ServiceWorkerContainer interface creates or updates a ServiceWorkerRegistration for the given scriptURL.
If successful, a service worker registration ties the provided script URL to a scope, which is subsequently used for navigation matching. You can call this method unconditionally from the controlled page. I.e., you don't need to first check whether there's an active registration.
所以你应该总是在你的页面上调用register
。浏览器 API 将为您处理此问题。
关于javascript - 如何让 service worker 只在第一次访问时注册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636941/