简体   繁体   中英

Why does my service worker cache pages even if I disable it?

I develop the static website francoscarpa.com using Eleventy . This website uses a service worker to provide offline capabilities to the user. All my pages are rendered through this template:

<!DOCTYPE html>
<html>
   <head>...</head>
   <body>
   ...
   <footer>...</footer>
   {% include "swRegistration.html" %}
   </body>
</html>

swRegistration.html has this content:

<script>
   if ("serviceWorker" in navigator) {
      window.addEventListener("load", function () {
         ...
         navigator.serviceWorker.register("/sw.js");
      });
   }
</script>

It basically lets me use the service worker. The content of the sw.js file is this:

const CACHE_NAME = "static12";
const STATIC_FILES = [ ... ]; // the resources to cache

self.addEventListener("install", function (event) { ...  });
self.addEventListener("activate", function (event) { ... });
self.addEventListener("fetch", function (event) { ... });

What I don't understand is why the service worker caches the resources even when I disable the {% include "swRegistration.html" %} line from the generated HTML files:

<html>
   <head>...</head>
   <body>
   ...
   <footer>...</footer>
   <!-- {% include "swRegistration.html" %} -->
   </body>
</html>

If I comment that line out, the rendered HTML pages correctly don't show it and when I start Eleventy's live-reload web server during development, the line is not present:

在此处输入图像描述

but analyzing the page with Firefox's Inspector, I see the static12 cache is still there after every page refresh, even after I manually delete it:

在此处输入图像描述

A service worker has a lifecycle independent from normal JavaScript code executed during a page visit. Once the service worker is registered, it doesn't get removed just because you commented out the code that registered it. So in your case, the service worker was probably already registered, which is why you're still seeing the cache being created after commenting out the registration code.

You can check if this is the case by going to the Application tab in Firefox's DevTools and checking if your service worker shows up as registered. In this case, you should also see a button to manually unregister it. In older versions of Firefox (the Application tab is a recent addition), you can open about:debugging in a new tab instead, which will also show you the list of registered service workers.

If your service worker has already been used on the live site and you want to remove it, you should put in some code to programmatically unregister the service worker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM