首页 > 解决方案 > 为什么 Safari 向服务人员发送两次图像请求?

问题描述

就我的测试而言,这似乎是 Safari 唯一的问题。我创建了一个服务工作者,它缓存一组页面以供离线/后备使用。在具有清晰缓存的全新导航上,所有内容都将按预期工作。Service Worker 将安装、缓存必要的页面、激活并开始监听 fetch 事件。这是事情变得奇怪的时候。如果我然后刷新页面或导航到站点上的任何其他页面,服务工作者将按预期拦截请求,但图像文件(在我的情况下是 GIF)将被请求两次。然后它变得更加奇怪。关闭该站点,然后导航回该站点,重复图像请求的问题将得到解决。然而,仍然出乎意料的是,服务工作者将拦截文档(该部分是预期的),但其他所有内容(图像、JS、CSS)将从 memory_cache 提供。我没有体验过 Chrome 或 Mozilla 的行为类型。

swCache.js

var cacheName = 'v1';

var fallback = {'/':'/index_OFFLINE.php', '/index.php':'/index_OFFLINE.php', '/reportgenerator':'/reportgenerator/index_OFFLINE.php', '/reportgenerator/':'/reportgenerator/index_OFFLINE.php', '/reportgenerator/1DayDataEntry.php':'/reportgenerator/1DayDataEntry_OFFLINE.php'};

var cacheAssets = ['/login.php', '/index_OFFLINE.php', '/reportgenerator/index_OFFLINE.php', '/reportgenerator/1DayDataEntry_OFFLINE.php', '/the_pump_new.gif', '/The-Pump.gif', '/thePumpCloud.gif', '/the_pump_new.ico', '/h2osoftwarestyle.css', '/h2osoftwareJS.js'];

self.addEventListener('install', e => {
    console.log('Service Worker Installed');
    
    e.waitUntil(
        caches.open(cacheName)
        .then(cache => {
            console.log('Service Worker Caching Files');
            cache.addAll(cacheAssets);
        })
        .then(() => self.skipWaiting())
    );
});

self.addEventListener('activate', e => {
    console.log('Service Worker Activated');
    
    e.waitUntil(
        caches.keys()
        .then(cacheNames =>{
            return Promise.all(
                cacheNames.map(cache => {
                    if(cache != cacheName){
                        console.log('Service Worker Clearing Old Cache');
                        return caches.delete(cache);
                    }
                })
            );
        })
    );
});

self.addEventListener('fetch', e => {
    console.log('Service Worker Fetching'); 
    
    e.respondWith(
        fetch(e.request)
        .catch(() => {
            var matchReq;
    
            var swReqURL = new URL(e.request.url);
            var swReqURLPath = swReqURL.pathname;
            
            if(cacheAssets.includes(swReqURLPath)){
                matchReq = e.request;
            }else if(fallback[swReqURLPath]){
                matchReq = fallback[swReqURLPath];
            }else{
                matchReq = '/index_OFFLINE.php';
            }
            return caches.match(matchReq);
        })
    );
});

任何帮助,将不胜感激!

标签: javascriptphpsafariservice-worker

解决方案


推荐阅读