在PWA中实施了Service Worker,但没有离线启动

时间:2019-12-10 07:13:51

标签: javascript android service-worker progressive-web-apps

我创建了一个PWA。 Google Chrome浏览器审核说,一切正常。但是离线启动应用程序时出现问题。 情况如下:一旦我在线下载PWA,然后我在线打开应用程序,一切正常。然后,我(完全)关闭该应用程序,然后脱机并离线启动该应用程序,它运行良好。但是,当我离线并完全关闭该应用程序并等待大约10分钟时(这很重要,因为仅当我等待某个时间此现象被发现时)并想启动该应用程序(离线!),该应用程序将无法加载。 (使用android)

这是我的服务人员:

const CACHE_NAME = 'myApp';

//Preload UI5 core and libraries by install
const cdnBase = 'myressroucelink.com';
var RESOURCES_TO_PRELOAD = [
    'Component-preload.js',
    'index.html',
    `${cdnBase}ui-core.js`,
    `${cdnBase}ui/core/library-preload.js`,
    `${cdnBase}m/themes/belize/library.css`,
    `${cdnBase}ui/core/themes/base/fonts/icons.woff2`,
    `${cdnBase}m/library-preload.js`,
    `${cdnBase}ui/core/themes/belize/library.css`
];

// Preload some resources during install
self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(CACHE_NAME).then(function (cache) {
            return cache.addAll(RESOURCES_TO_PRELOAD);
        })
    );
});

// Delete obsolete caches during activate
self.addEventListener('activate', function (event) {
    event.waitUntil(
        caches.keys().then(function (keyList) {
            return Promise.all(keyList.map(function (key) {
                if (key !== CACHE_NAME) {
                    return caches.delete(key);
                }
            }));
        })
    );
});

// During runtime, get files from cache or -> fetch, then save to cache
self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.match(event.request).then(function (response) {
            if (response) {
                return response; // There is a cached version of the resource already
            }

            // if not found in cache, return default offline content (only if this is a navigation request)
            if (event.request.mode === 'navigate') {
                return caches.match('./index.html');
            }

            let requestCopy = event.request.clone();
            return fetch(requestCopy).then(function (response) {
                if (!response) {
                    return response;
                }
                // If a resource is retrieved, save a copy to the cache.
                // Unfortunately, it is not possible to check if the response form CDN
                // was successful (responses with type === 'opaque' have zero status).
                // For example, a 404 CDN error will be cached, too.
                if (response.status === 200 || response.type === 'opaque') {
                    let responseCopy = response.clone();
                    caches.open(CACHE_NAME).then(function (cache) {
                        cache.put(event.request, responseCopy);
                    });
                }
                return response;
            });
        })
    );
});

这与缓存有关还是我的服务人员有问题?

0 个答案:

没有答案