How to register service worker?

问题: I can not register a service worker. The file is located along with the index.js and app.js. I get next errors A bad HTTP response code (404) was received when fetching t...

问题:

I can not register a service worker. The file is located along with the index.js and app.js. I get next errors

A bad HTTP response code (404) was received when fetching the script.

Failed to load resource: net::ERR_INVALID_RESPONSE

Registration failed TypeError: Failed to register a ServiceWorker: A 
bad HTTP response code (404) was received when fetching the script.

****** 
    if ('serviceWorker' in navigator) {
        window.addEventListener('`load`', () => {
        navigator.serviceWorker.register('serviceWorker.js', { scope:'./' })
            .then((registration) => {
                console.log('Registration completed successfully',registration);
            })
            .catch((error) => {
                console.log('Registration failed', error);
            })
     })}

回答1:

It not only have to be along side index.js and app.js, it has to be in the root of your application. so if it happens your index.js or app.js are in a folder say js, it wont work. just put serviceWorker.js in the same directory as index.html and please run it in a server

Why is this? I am not an expert at this, but I know service workers are used to serve all your files on an offline scenerio. If you put it as a relative path, it's going to be tricky to map to all other files outside.

This is not a rule though, you can somehow find a way to put your serviceWorker in some subfolder, but I personally don't consider this a best practice

  • 发表于 2019-03-02 14:47
  • 阅读 ( 732 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除