Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make service worker register only on the first visit?

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>
like image 407
Vishak Uday Avatar asked Jun 01 '18 05:06

Vishak Uday


Video Answer


1 Answers

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.

like image 177
krampstudio Avatar answered Oct 20 '22 18:10

krampstudio