脱机和缓存被删除时的脱机页面

时间:2018-08-09 22:03:52

标签: javascript service-worker

我的服务人员看起来像这样:

    const staticCacheName = 'restaurant-cache-v6';
    const OFFLINE_URL = 'offline.html';
    const filesToCache = [

     '/',
      './manifest.json',
       './index.html',
     './offline.html',
     './restaurant.min.html',
     './css/styles.min.css',
     './js/lazyload.min.js',
     './js/idb.min.js',
     './js/dbhelper.min.js',
     './js/main.min.js',
     './js/restaurant_info.min.js',
     './data/restaurants.json',
     './img/1.jpg',
    ];  
    
    self.addEventListener('install', function (e) {
     console.log('[ServiceWorker] Install');
        e.waitUntil(caches.open(staticCacheName).then(function (cache) {
            console.log('Cache is opened');
            return cache.addAll(filesToCache);
        })
        );
    });

    self.addEventListener('active', function (e) {
        e.waitUntil(
            caches.keys().then(function (cacheNames) {
                return Promise.all(
                    cacheNames.filter(function (cacheName) {
                        return cacheName.startsWith('restaurant-') && cacheName != staticCacheName;
                    }).map(function (cacheName) {
                        return caches.delete(cacheName);
                   })
             );
         }))
    });


    self.addEventListener('fetch', function (e) {
        {
            e.respondWith(
                caches.match(e.request, { ignoreSearch: true }).then(function (res) {//now works with query string in the URL.  !!!!
                    if (res) {
                        return res;
                    }
                    var fetchReq = e.request.clone();
                    return fetch(fetchReq).then(
                        function (res) {
                            if (!res || res.status !== 200 || res.type !== 'basic') {
                                return res;
                          }
                            var resToCache = res.clone();
                            caches.open(staticCacheName)
                                .then(function (cache) {
                                    cache.put(e.request, resToCache);
                                });
                          return res;
                        }
                    );
                })
            );
     }
    }); 

    self.addEventListener('message', function (e) {
        if (e.data.action === 'skipWaiting') {
            self.skipWaiting();
        }
    });


一切正常,SW注册,当我离线切换devtools时,它从缓存中获取-我的页面看起来像在线 但是当我脱机并清除所有缓存时,我得到了:

一切正常,SW注册,当我离线切换devtools时,它从缓存中获取-我的页面看起来像在线 但是当我脱机并清除所有缓存时,我得到了:

enter image description here

是否可以通过sw渲染OFFLINE_URL网站?

0 个答案:

没有答案