Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 340
Estus Flask Avatar asked Dec 07 '18 08:12

Estus Flask


Video Answer


2 Answers

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.

like image 175
abraham Avatar answered Sep 17 '22 19:09

abraham


It's not that blocking with load event listener.

you need to load all resources anyway and the service worker stores them afterwards in the browser.

next time the user visits the application, the service worker is already there. Ready to deliver resources from the browser's cache.

the service worker is not running with the main thread.

like image 40
André Kelling Avatar answered Sep 19 '22 19:09

André Kelling