lundi 13 décembre 2021

Why service worker's fetch event handler not being called but still worked?

I'm new to Service Worker, I tried to write some code to learn how to use Service Worker but I found something weird with fetch event handler, these are my pieces of code:

(Html file and js file are hosted by nginx with self-signed certificate made with mkcert, I use https://localhost to visit the page)

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>test</title>
</head>
<body>
  <script>
    window.addEventListener('DOMContentLoaded', () => {
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.ready.then(() => {
          console.log('sw ready');
        });
        
        navigator.serviceWorker.register('/sw.js')
        .then(() => {
          console.log('sw registered');
        });
      }
    });
  </script>
</body>
</html>

sw.js:

self.addEventListener('install', event => {
  console.log('sw install');

  event.waitUntil(
    caches.open('v1').then(cache => {
      cache.addAll([
        './'
      ])
    })
  );
});

self.addEventListener('activate', () => {
  console.log('sw activate');
});

self.addEventListener('fetch', event => {
  console.log('sw fetch'); // Line 1

  event.respondWith(caches.match(event.request)); // Line 2
});

I added console.log() at the beginning of each callback function, so when those callback functions being called, something should be printed to the console.

The weird thing is about the 'Line 1' and 'Line 2' in the callback of fetch event handler.

The first try

I write and test codes with Browser's DevTool opened with 'Disable cache' checked, when I run the above codes first time (with all caches cleaned), I got the following output:

(index):16    sw registered
sw.js:2       sw install
sw.js:14      sw activate
(index):11    sw ready

Then I toggled the Network offline in the 'Network' tab in DevTool, pressed 'F5' refreshed the page, the page displayed normally as expected and I got the following output:

(index):11    sw ready
(index):16    sw registered

Evetything looks fine. According to the output, the fetch event handler was not called in the above process, because if the fetch event handler was called, there must be a 'sw fetch' appear in the output.

The second try

So I comment the 'Line 2' like this:

self.addEventListener('fetch', event => {
  console.log('sw fetch'); // Line 1

  // event.respondWith(caches.match(event.request)); // Line 2
});

If my 'fetch' event handler was not called, it should be ok to remove some codes from it.

I toggled the Network back to online, closed the tab, cleaned all browser caches and visited https://localhost again, the page displayed and I got the following output:

sw.js:2       sw install
(index):16    sw registered
sw.js:14      sw activate
(index):11    sw ready

Then I toggled the Network offline again, pressed 'F5' to refresh the page, the page did not displayed, and I got the following output:

There is no output, and wait for some seconds I got this:

(2)sw.js:18    sw fetch

Then I checked the 'Network' tab, I found these things:

enter image description here

I think the two 'sw fetch' was caused by the last two canceled requests to 'localhost'.

What I observed really confused me. The 'Line 2' must have worked somehow, otherwise when I comment the 'Line 2' in my second try, the page should displayed normally like what I got in my first try.

Question is, if 'Line 2' did work, I think it means 'Line 2' was executed, which means the 'fetch' event handler was called, at least one 'sw fetch' should appear in the console in my first try.

But in my first try I did not get any 'sw fetch' log output. It looks like my browser 'magically' skiped the console.log() (Line 1) in my 'fetch' event handler and just executed event.respondWith() (Line 2), which seems dis-obey the execution order of code.

It's so weird, can someone help explain what happens here? Thanks.

Something about my environment:

  • Browser: Version 96.0.1054.53 (Official build) (64-bit)
  • System: Windows 10 Home Edition 20H2



Aucun commentaire:

Enregistrer un commentaire