最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why service worker's fetch event handler not being called but still worked? - Stack Overflow

programmeradmin4浏览0评论

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 ment 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 ment 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

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 ment 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 ment 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
Share Improve this question edited Dec 13, 2021 at 7:52 LittleSaya asked Dec 13, 2021 at 7:11 LittleSayaLittleSaya 3081 gold badge3 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

I'd remend reading through "The Service Worker Lifecycle" for a great foundational introduction to service workers.

That article describes a method, clients.claim(), that you can call to cause a newly activated service worker to take control of all open clients:

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

If a service worker is in control, network requests originating from the client will trigger the fetch handler.

If you don't call clients.claim(), then the service worker won't control the client that registered it for the first time, and I think that explains what you're seeing.

发布评论

评论列表(0)

  1. 暂无评论