安装时的ServiceWorker缓存

时间:2017-08-05 07:43:21

标签: html5 service-worker

我试图找出如何在安装时缓存动态页面?我当前的页面是/product/1/view

self.addEventListener('install', function (event) {
event.waitUntil(
        caches.open('kiosk-assets').then(function (cache) {
            return cache.addAll([
                '/' // This is the problem it caches the origin path i need the current page cached. See register below
                '/css/product.min.css'
            ])
        }),
....

以下是我如何注册我的工作人员。这是在/product/1/view

上注册的
window.navigator.serviceWorker.register('/sw.js', {scope: `/product/${id}/view`})

如果可能的话,我可以改变注册方式。

2 个答案:

答案 0 :(得分:1)

我不认为,你可以这样做onInstall

至少不与服务工作者本身有关。原因很简单,在安装服务工作者时,它不知道它控制/将控制哪些客户端。

此外,即使是活跃的服务人员也无法控制DOM。 因此,它无法知道当前的网址是什么。

您可以在activate和/ fetch事件

上缓存网址

或,

您需要客户端ping工作人员,同时安装它。

如果您只需要严格缓存注册页onInstall,那么,

通过postMessage从注册工作人员的页面发送消息

if ( 'serviceWorker' in navigator ) {
navigator.serviceWorker.register( 'sw.js' )
    .then( function ( success ) {
        console.log( 'scope', success.scope );
        if ( success.installing ) {
            let sw = success.installing;
            sw.addEventListener( 'statechange', function ( event ) {
                if ( event.target.state == 'installed' ) {
                    let loc = window.location.toString();
                    let message = {
                        action: 'cache',
                        location: loc
                    }
                    sw.postMessage( message );
                }
            } )
        }
    } );
}

并使用worker中的message事件来缓存网址

答案 1 :(得分:0)

You should probably use sw-precache library for static and dynamic caching of data.

Integrate it with you build environment (Gulp, Grunt, Webpack). Sw-precache serves all your static files and update it accordingly. sw-precache has the options of runtime-caching which fill fulfill your needs

You can learn about the library here - https://github.com/GoogleChrome/sw-precache

相关问题