微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在每次获取之前触发 Service Worker 安装事件,但未对 Service Worker 进行任何更改

如何解决在每次获取之前触发 Service Worker 安装事件,但未对 Service Worker 进行任何更改

根据 Service Worker 文档,每个 Service Worker 安装事件应该只触发一次;但是,如果我将 console.log 放在安装事件侦听器中,我会注意到在获取发生之前,安装事件总是被触发。

为什么即使软件没有更改/更新,服务工作者的安装事件也会被调用。如果服务工作者的安装事件在短时间内闲置,它会被调用吗?这是一个问题,因为缓存是在安装期间完成的,如果安装事件在获取发生之前被调用,我们会在根本不需要更新缓存时不断更新缓存。

感谢您的帮助!

const CACHE_NAME = 'my-cache-v2';
const cacheAllowList = [CACHE_NAME];
const externalFiles = [
    varIoUs files here
];


self.addEventListener('fetch',function (event) {
    event.respondWith(
        self.caches
            .match(event.request)
            .then(function (response) {
                if (response) {
                    return response;
                }
                return fetch(event.request);
            })
    );
});

self.addEventListener('install',function (event) {
    // Perform install steps
    event.waitUntil(
        self.caches.keys().then(function (cacheNames) {
                // Add cache
                self.caches.open(CACHE_NAME).then((cache) => {
                    return cache.addAll([
                        ...externalFiles
                    ]);
                })
                    .catch(error => {
                        console.log('Service worker cache Failed: ' + error);
                    })
        })
    );
});


self.addEventListener('activate',function (event) {

    // All caches not listed here will be deleted.

    event.waitUntil(
        self.caches.keys().then(function (cacheNames) {
            return Promise.all(
                cacheNames.map(function (cacheName) {
                    if (cacheAllowList.indexOf(cacheName) === -1) {
                        return self.caches.delete(cacheName);
                    }
                })
            );
        })
    );
});

self.addEventListener('push',function(event) {
    console.log('[Service Worker] Push Received.');
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

    const title = 'Push Codelab';
    const options = {
        body: 'Push notifications',icon: 'images/icon.png',badge: 'images/badge.png'
    };

    event.waitUntil(self.registration.showNotification(title,options));
});

*Edit - 需要注意的是,这并不总是发生。有时在不调用 install 的情况下 fetch 工作正常,有时在 fetch 发生之前似乎没有任何原因地调用 install。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。