Understanding ServiceWorker Registration

I am reading ServiceWorker starting docs https://developers.google.com/web/fundamentals/getting-started/primers/service-workers .

So, first we register our ServiceWorker with scope. So I did it like below

<!DOCTYPE html>
<html>
<head>
    <title>Getting started with Service Worker</title>
</head>
<body>

<script type="text/javascript">

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}    

</script>

</body>
</html>

and created the sw.js file and wrote console.log inside sw.js

console.log("This is sw.js")

So, when I first run the index.html file, console.log starts and a successful ServiceWorker message is printed. But when I refresh the page a second time, it only prints the ServiceWorker message successfully. So why didn't he execute console.log inside sw.js a second time. I expected him to execute this console.log a second time. Did I miss the point here?

+4
2

- , ( ), . - , API- :

- , , .

navigator.serviceWorker.register('/sw.js'); Promise, callback (, console.log('ServiceWorker registration successful ...');).

+3

. , , script , .

"fetch", . , console.log , , :

self.addEventListener('fetch', event => {
  console.log(event);
})
+1

Source: https://habr.com/ru/post/1678536/


All Articles