Hi I have an ejs template on express which generates HTML. I have written my service worker registration code in this template which is common for all pages of the website and thus, the registration code ends up being there on every page of the website. So, on every user visit, the service worker registration code is run which I believe is bad. How to make this code run only on the first visit of a user?
Please find my code below:
<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>
From the MDN documentation :
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.
So you should always call register
on your page. The browser API will handle this for you.
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