Search code examples
javascriptservice-workeroffline-mode

Where to put ServiceWorker snippet - head or body?


I'm starting with service-workers (a bit late to the party, but better then never), and I place my <script>if ('serviceWorker' in navigator) {..}</script> snippet at the very bottom, bellow my other snippet (System.import(...)).

Is that a good place for it? Where else should I put the standard script snippet on a page: head or maybe start of body? Or put it externally in another script?

More important - why?


Solution

  • Depending on how heavyweight your service worker is, and how much JavaScript needs to execute on your page during the initial visit, it may or may not make a difference. But you can read this article on service worker registration best practices for more insight as to when it might matter.

    The takeaway from the article is that a reasonable pattern is to use

    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js');
      });
    }
    

    to register your service worker. That could appear pretty much anywhere on your page, as long as it runs before the load event is fired.