【问题标题】:Service worker only fetches url from cache when adding "index.html"Service Worker 仅在添加“index.html”时从缓存中获取 url
【发布时间】:2019-08-07 12:12:51
【问题描述】:

我使用服务人员离线提供内容。以下代码运行良好,除非我在以在线模式打开和安装 serviceworker 后立即以离线模式刷新页面。 所有这些场景都有效: 1.在线加载页面,在线刷新页面->离线刷新页面-有效。 2. 在线加载“/offline-test/” -> 离线加载“/offline-test/index.html” - 有效 3. 在线加载“/offline-test/index.html/” -> 离线加载“/offline-test/” - 有效 只有这种情况不起作用: 在线加载页面 -> 在离线模式下刷新页面。

为什么?

我正在使用 Chrome 开发工具来模拟离线模式。 Firefox 中的同样问题(加载页面后关闭 WiFi)。

index.html

<HTML>
...
<BODY>
...
</BODY>
<SCRIPT>
        if('serviceWorker' in navigator) {
            navigator.serviceWorker.register('../sw.js')
                .then(function() {
                    console.log("Service Worker Registered");
                });
        }

    </SCRIPT>
</HTML>

sw.js

self.addEventListener('install', function(e) {
//  self.skipWaiting();

    if(navigator.onLine) {
        console.log('Navigator is online');
        e.waitUntil(caches.keys()
            .then(function(keyList) {
                console.log('Try to delete cache.');
                return Promise.all(keyList.map(function(key) {
                    return caches.delete(key)
                        .then(function(response) {
                            console.log('Cache-Key '+key+' will be deleted');
                            return response;
                        }, function(reject) {
                            consoloe.log('Failure deleting '+key);
                            return reject;
                        });
                }))
            })
        );
    }

    e.waitUntil(
        caches.open('offline-test-v3').then(function(cache) {
            console.log('index.html and all the others will be added to cache');
            return cache.addAll([
                'offline-test/',
                'offline-test/index.html',
                'offline-test/style.css',
                'offline-test/logo-192.png',
                'offline-test/fonts/ROCK.TTF',
                'manifest.json',
                'offline-test/favicon.ico'
            ])
                .then(function(response) {
                    console.log('Everything succesfully added to cache');
                });
        })
    );
});

self.addEventListener('activate', function(ev) {
//  ev.waitUntil(self.clients.claim());
//  clients.claim();
//  ev.waitUntil(clients.claim());
    console.log('I\'m activated');
});

self.addEventListener('update', function(eve) {
    console.log('I\'m updated');
});

self.addEventListener('fetch', function(event) {
    console.log('Will fetch '+event.request.url);
    //Networ first
    event.respondWith(
        fetch(event.request).catch(function() {
            console.log('Try to fetch '+event.request.url+' from cache');
            return caches.match(event.request);
        })
    );

在线加载 index.html 后的控制台

Service Worker Registered
sw.js:9 Navigator is online
sw.js:12 Try to delete cache.
sw.js:29 index.html and all the others will be added to cache
sw.js:40 Everything succesfully added to cache
sw.js:58 I'm activated

离线模式下刷新后的控制台

Will fetch index.html
sw.js:70 Try to fetch [url]/index.html from cache
The FetchEvent for [url]/index.html" resulted in a network error response: an object that was not a Response was passed to respondWith().

【问题讨论】:

    标签: javascript caching service-worker page-refresh


    【解决方案1】:

    通过添加新缓存作为对前面缓存删除例程的解析来解决此问题。 可能这两个线程有​​冲突。

    新的 sw.js

    self.addEventListener('install', function(e) {  
        if(navigator.onLine) {
            console.log('Navigator is online');
            e.waitUntil(caches.keys()
            .then(function(keyList) {
                console.log('Try to delete cache.');
                return Promise.all(keyList.map(function(key) {
                    return caches.delete(key)
                        .then(function(response) {
                            console.log('Cache-Key '+key+' will be deleted');
                            return response;
                        }, function(reject) {
                            consoloe.log('Failure deleting '+key);
                            return reject;
                        });
                }))
            })
            .then(function() {
                caches.open('offline-test-v3').then(function(cache) {
                    console.log('index.html and all the others will be added to cache');
                    return cache.addAll([
                        'offline-test/',
                        'offline-test/index.html',
                        'offline-test/style.css',
                        'offline-test/logo-192.png',
                        'offline-test/fonts/ROCK.TTF',
                        'manifest.json',
                        'offline-test/favicon.ico'
                    ])
                    .then(function(response) {
                        console.log('Everything succesfully added to cache');
                    });
                })
            }));
        }
    });
    
    self.addEventListener('activate', function(ev) {
        console.log('I\'m activated');
    });
    
    self.addEventListener('update', function(eve) {
        console.log('I\'m updated');
    });
    
    self.addEventListener('fetch', function(event) {
        console.log('Will fetch '+event.request.url);
        //Network first
        event.respondWith(
            fetch(event.request)
                .then(function(resolve) {
                    console.log('Fetched '+event.request.url+' via the browser way.');
                    return resolve;
                }, function(reject) {
                    console.log('Try to fetch '+event.request.url+' via the serviceworker way');
                    return caches.match(event.request);
                })
            );
    /*  if(!navigator.onLine) {
            console.log('Try to fetch '+event.request.url+' from cache.');
            event.respondWith(caches.match(event.request)
                .then(function(response) {
                    return response || fetch(event.request);
                })
            );
        }*/
    
    });
    

    【讨论】:

      猜你喜欢
      • 2020-02-10
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2018-03-29
      • 2020-12-06
      • 1970-01-01
      相关资源
      最近更新 更多