Javascript 如何将服务人员预抓取与跨导航抓取结合起来?

Javascript 如何将服务人员预抓取与跨导航抓取结合起来?,javascript,google-chrome,caching,asynchronous,service-worker,Javascript,Google Chrome,Caching,Asynchronous,Service Worker,我尝试使用“预取”和“收集”技术在SPA应用程序上缓存js、CSS和内容 对于预取脚本,我尝试了类似以下代码片段的代码: self.addEventListener('install',函数(事件){ var now=Date.now(); 变量urlsToPrefetch=[ “static/pre_fetched.txt”, “static/pre_fetched.html” ]; event.waitill( 缓存。打开(当前缓存。预取)。然后(函数(缓存){ var cacheProm

我尝试使用“预取”和“收集”技术在SPA应用程序上缓存js、CSS和内容

对于预取脚本,我尝试了类似以下代码片段的代码:

self.addEventListener('install',函数(事件){
var now=Date.now();
变量urlsToPrefetch=[
“static/pre_fetched.txt”,
“static/pre_fetched.html”
];
event.waitill(
缓存。打开(当前缓存。预取)。然后(函数(缓存){
var cachePromises=urlsToPrefetch.map(函数(urlToPrefetch){
var url=新url(urlToPrefetch,location.href);
url.search+=(url.search?'&':'?')+“缓存半身像='+现在;
var request=新请求(url,{mode:'no cors'});
返回fetch(请求)。然后返回函数(响应){
如果(response.status>=400){
抛出新错误('请求'+urlToPrefetch+
“失败,状态为”+响应。状态文本);
}
返回cache.put(urlToPrefetch,response);
}).catch(函数(错误){
console.error('由于'+错误而未缓存'+urlToPrefetch+');
});
});
返回Promise.all(cachePromises).then(function(){
log('Pre-fetching complete');
});
}).catch(函数(错误){
console.error('预取失败:',错误);
})
);

});我没有找到任何参考来确认我的解决方案,但是,它是有效的

解决方案是创建2个不同的缓存,并“规范化”请求将其克隆到syntetic请求中,删除所有引用,只保留基本的:

var CURRENT_CACHES = {
    'prefetch-cache': 'prefetch-cache-v' + CACHE_VERSION, //Prefetch cach
    'general-cache': 'general-cache-v' + CACHE_VERSION,
};
预回迁缓存
负责存储我想要在我的服务人员上预回迁的所有文件,而普通缓存则用于所有其他文件(当您有SPA并且想要累积一些请求,如翻译文件、js组件、css和其他内容时,这是有意义的)

您可以使用要预回迁的所有文件的URI创建一个数组:

var urlsToPrefetch = [
    //JS
    "plugin/angular/angular.min.js", "plugin/requirejs/require.min.js","app/main.js","app/app.js","app/includes.js"
    //CSS
    ,"styles/css/print.css","styles/css/bootstrap.css","styles/css/fixes.css",
    //Html
    ,"app/layout/partials/menu.tpl.html",  "app/layout/public.tpl.html",
    //JSON
    ,"app/i18n/languages.json","app/i18n/pt-br.json", "app/i18n/en.json"
];
在install event中,您应该为此阵列中的所有文件创建新请求,并将其存储到预回迁缓存中:

self.addEventListener('install', function (event) {
    logger && console.log('Handling install event:', event);

    //var now = Date.now();

    // All of these logging statements should be visible via the "Inspect" interface
    // for the relevant SW accessed via chrome://serviceworker-internals   
    if (urlsToPrefetch.length > 0) { 
        logger && console.log('Handling install event. Resources to prefetch:', urlsToPrefetch.length , "resources");
        event.waitUntil(
                caches.open(CURRENT_CACHES['prefetch-cache']).then(function (cache) {
            var cachePromises = urlsToPrefetch.map(function (urlToPrefetch) {
                urlToPrefetch +=  '?v=' + CACHE_VERSION;
                // This constructs a new URL object using the service worker's script location as the base
                // for relative URLs.
                //var url = new URL(urlToPrefetch + '?v=' + CACHE_VERSION, location.href);
                var url = new URL(urlToPrefetch, location.href);
                // Append a cache-bust=TIMESTAMP URL parameter to each URL's query string.
                // This is particularly important when precaching resources that are later used in the
                // fetch handler as responses directly, without consulting the network (i.e. cache-first).
                // If we were to get back a response from the HTTP browser cache for this precaching request
                // then that stale response would be used indefinitely, or at least until the next time
                // the service worker script changes triggering the install flow.
                //url.search += (url.search ? '&' : '?') + 'v=' + CACHE_VERSION;

                // It's very important to use {mode: 'no-cors'} if there is any chance that
                // the resources being fetched are served off of a server that doesn't support
                // CORS (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing).
                // In this example, www.chromium.org doesn't support CORS, and the fetch()
                // would fail if the default mode of 'cors' was used for the fetch() request.
                // The drawback of hardcoding {mode: 'no-cors'} is that the response from all
                // cross-origin hosts will always be opaque
                // (https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cross-origin-resources)
                // and it is not possible to determine whether an opaque response represents a success or failure
                // (https://github.com/whatwg/fetch/issues/14).
                var request = new Request(url, {mode: 'no-cors'});
                return fetch(request).then(function (response) {
                    logger && console.log('Add to Cache (Prefetch)', url.href);


                    if (!response || response.status !== 200 || response.type !== 'basic') {
                        throw new Error('request for ' + urlToPrefetch +
                                ' failed with status ' + response.statusText);
                    }
                    //var responseToCache = response.clone();

                    // Use the original URL without the cache-busting parameter as the key for cache.put().
//                    return cache.put(urlToPrefetch, responseToCache);
                    return cache.put(urlToPrefetch, response);
                }).catch(function (error) {
                    logger && console.error('Not caching ' + urlToPrefetch + ' due to ' + error);
                });
            });

            return Promise.all(cachePromises).then(function () {
                logger && console.log('Pre-fetching complete.');
            });
        }).catch(function (error) {
           logger && console.error('Pre-fetching failed:', error);
        }));
    }

    // Perform install steps
//    if (urlsToPrefetch.length > 0) {
//        event.waitUntil(
//                caches.open(CURRENT_CACHES['perma-cache'])
//                .then(function (cache) {
//                    return cache.addAll(urlsToPrefetch);
//                })
//                );
//    }
    // `skipWaiting()` forces the waiting ServiceWorker to become the
    // active ServiceWorker, triggering the `onactivate` event.
    // Together with `Clients.claim()` this allows a worker to take effect
    // immediately in the client(s).
    return self.skipWaiting();
});
对于将来将存储在缓存中的所有其他文件,您必须将其声明为fetch event listener,并将此请求存储到常规缓存中:

self.addEventListener('fetch', function (event) {
    //console.log(event);
    if (event.request.method === "GET") {
        var qSFilter = "" + ((event.request.url).split('?'))[0];//Filtrar Quetry Stirng
        //console.log(event.request.url, qSFilter, qSFilter.split(CACHE_SCOPE), CACHE_SCOPE);
        var leUrl = (qSFilter.split(CACHE_SCOPE))[1];
        //Is possible to implement some logic to skip backend calls and other uncachable calls
        if (/^(app|style|plugin).*(js|css|html|jpe?g|png|gif|json|woff2?)$/.test(leUrl)
                || /^backend\/server\/file\/i18n\/((?!client).+)\//.test(leUrl)
                || /^backend\/server\/static\/images\/.*$/.test(leUrl)
                || /^backend\/server\/static\/style.*$/.test(leUrl)
                ) {
            var url = new URL(leUrl + '?v=' + CACHE_VERSION, location.href);
            var synthetic = new Request(url, {mode: 'no-cors'});
            //console.log(event.request,response.clone(),synthetic);
            event.respondWith(
//                    caches.match(event.request)
                    caches.match(synthetic)
                    .then(function (response) {
                        // Cache hit - return response
                        if (response) {
                            logger && console.log('From Cache', event.request.url);
                            return response;
                        }

                        // IMPORTANT: Clone the request. A request is a stream and
                        // can only be consumed once. Since we are consuming this
                        // once by cache and once by the browser for fetch, we need
                        // to clone the response
                        var fetchRequest = event.request.clone();

                        return fetch(fetchRequest).then(
                                function (response) {
                                    // Check if we received a valid response
                                    if (!response || response.status !== 200 || response.type !== 'basic') {
                                        return response;
                                    }

                                    // IMPORTANT: Clone the response. A response is a stream
                                    // and because we want the browser to consume the response
                                    // as well as the cache consuming the response, we need
                                    // to clone it so we have 2 stream.
                                    var responseToCache = response.clone();

                                    caches.open(CURRENT_CACHES['general-cache'])
                                            .then(function (cache) {
                                                try {
                                                    logger && console.log('Add to Cache', event.request.url, qSFilter,leUrl);
                                                    cache.put(event.request, responseToCache);
                                                } catch (e) {
                                                    console.error(e);
                                                }
                                            });

                                    return response;
                                }
                        );
                    })
                    );
        }
    }
});
可在此处访问完整的工作脚本: