没有下次刷新

时间:2017-08-24 22:12:32

标签: google-chrome service-worker

我正在学习如何使用服务工作者,我的问题是当第一次加载页面时点击按钮fetch()某些文件时没有触发任何fetch事件,但是手动刷新页面然后再次单击该按钮后,fetch事件将按预期触发

请指导如何解决此问题 感谢

  

Chrome:60

服务worker.js

self.addEventListener('install', event => {
    event.waitUntil(
        caches.open('XXX')
            .then(cache => {
                cache.allAll([ ... ])
            })
    )
})

self.addEventListener('activate', event => {
    console.log('ready')
})

self.addEventListener('fetch', event => {
    console.log('fetch')
})

的index.html

<body>
    <button id="btn" class="button">Click</button>

    <script>
    (() => {
        document.getElementById('btn').addEventListener('click', () => {
            fetch(' ... ')
                .then(res => {
                    return res.json()
                })
                .then(res => {
                    console.log(res)
                })
        })

        if (!('serviceWorker' in navigator)) {
            console.log('Service Worker is not supported')

            return
        }

        navigator.serviceWorker.register('/service-worker.js')
            .then((registration) => {
                console.log('Sevice Worker has been registered')
            })
    })()
    </script>
</body>

1 个答案:

答案 0 :(得分:1)

你可能需要self.clients.claim()来尽快激活service-worker。

self.addEventListener('activate', function(event) {
  event.waitUntil(self.clients.claim());
});

请参阅:What is the use of `self.Clients.claim()`