Search code examples
javascriptservice-workerprogressive-web-appsworkbox

Waiting for window load event to register service worker


I stumbled upon this snippet in Google Workbox documentation:

<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js');
  });
}
</script>

How exactly page load becomes less performant without window load event handler?

Wouldn't it be generally preferable for service worker to hook up as early as possible, since one of main uses for it in PWA is caching?


Solution

  • Service workers load in the background off the main thread but they still consume computer resources and, if pre-caching, network resources. If the current rendering page takes 500KB to render and and you want to pre-cache the page to fully work offline, the service worker will also have to download that 500KB. This competes with the current page being rendered so it's advised to delay registering a service worker until after the current page is ready for the user.

    You can read more about registering service workers on web fundamentals.