2

这是我的代码:

    var cacheName = 'app-cache-v2';
var filesToCache = [
    'wp-content/themes/ct/bootstrap.css',
    'wp-content/themes/ct/bootstrap-1024.css',
    'wp-content/themes/ct/bootstrap-1280.css',
    'wp-content/themes/ct/assets/js/jquery.min.js',
    'wp-content/themes/ct/assets/js/slick.js',
    'wp-content/themes/ct/assets/js/ctjs.js',
    'wp-content/themes/ct/bootstrap-640.css',
    'wp-content/themes/ct/assets/images/img-thumb.jpg',
    'wp-content/themes/ct/assets/images/logo-career-tutorial.jpg',
    'wp-content/themes/ct/assets/images/logo-career-tutorial.png',
    'wp-content/themes/ct/assets/fonts/pnsemib.woff2',
    'wp-content/themes/ct/assets/fonts/pnreg.woff2',
    'wp-content/themes/ct/assets/fonts/pnbold.woff2',
    'wp-content/themes/ct/assets/images/banner.jpg'
];

self.addEventListener('install', function(event){
    event.waitUntil(
        caches.open(cacheName).then(function(cache){
            return cache.addAll(filesToCache);
        }).then(function(){
            return self.skipWaiting();
        })
    );
});


self.addEventListener('activate', function(event){
    event.waitUntil(
        caches.keys().then(
            keyList => {
                return Promise.all(
                    keyList.map(
                        key=>{
                            if(key !== cacheName){
                                return caches.delete(key);
                            }
                        }
                    )
                );
            }
        )
    );
    return self.clients.claim();    
});

self.addEventListener('fetch', function(event){
    caches.open(cacheName).then(function(cache) {
    fetch(event.request)
    .then(function(response){
            const url = new URL (event.request.url);
            if(url.origin == location.origin){
                cache.add(event.request.url);
            }
        });
    });
});

self.addEventListener('fetch', event => {
  // Prevent the default, and handle the request ourselves.
  event.respondWith(async function() {
    // Try to get the response from a cache.
    const cachedResponse = await caches.match(event.request.url);
    // Return it if we found one.
    if (cachedResponse) return cachedResponse;
    // If we didn't find a match in the cache, use the network.
    return fetch(event.request, {mode: 'cors'});
  }());
});

控制台中显示的错误是:

无法加载“facebook 脚本”请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问来源“ https://www.careertuts.com ”。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

Uncaught (in promise) TypeError: Failed to fetch

加载资源失败:net::ERR_FAILED

加载资源失败:net::ERR_BLOCKED_BY_CLIENT

这是服务工作者注册的代码

navigator.serviceWorker && navigator.serviceWorker.register('/sw.js',{scope: '/'
}).then(function(registration) {
        console.log('Excellent, registered with scope: ', registration.scope);
    });
4

0 回答 0