如何在没有单独 JS 文件的情况下使用 ServiceWorker? [英] How do I use ServiceWorker without a separate JS file?

查看:64
本文介绍了如何在没有单独 JS 文件的情况下使用 ServiceWorker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们通过

navigator.serviceWorker.register('sw.js', { scope: '/' });

我们可以在没有外部文件的情况下创建新的 Workers

We can create new Workers without an external file like this,

var worker = function() { console.log('worker called'); };
var blob = new Blob( [ '(' , worker.toString() , ')()' ], {
    type: 'application/javascript'
});
var bloburl = URL.createObjectURL( blob );
var w = new Worker(bloburl);

通过使用 blob 创建 ServiceWorkers 的方法,我们会得到一个 Security Error,因为 bloburl 将是 blob:chrome-extension...,并且来源Service Worker 将不支持.

With the approach of using blob to create ServiceWorkers, we will get a Security Error as the bloburl would be blob:chrome-extension..., and the origin won't be supported by Service Workers.

是否可以在没有外部文件的情况下创建一个 Service Worker 并将范围用作 / ?

Is it possible to create a service worker without external file and use the scope as / ?

推荐答案

我强烈建议不要试图绕过 Service Worker 实现代码存在于独立文件中的要求.Service Worker 生命周期中有一个非常重要的内容,更新,它依赖于在您的浏览器上能够定期获取您注册的 Service Worker JavaScript 资源并进行逐字节比较以查看是否有任何更改.

I would strongly recommend not trying to find a way around the requirement that the service worker implementation code live in a standalone file. There's a very important of the service worker lifecycle, updates, that relies on your browser being able to fetch your registered service worker JavaScript resource periodically and do a byte-for-byte comparison to see if anything has changed.

如果您的 Service Worker 代码发生了变化,那么新代码将被视为 installing Service Worker,而旧的 Service Worker 代码最终将被视为 redundant Service Worker 尽快注册并卸载/关闭所有具有旧代码的页面.

If something has changed in your service worker code, then the new code will be considered the installing service worker, and the old service worker code will eventually be considered the redundant service worker as soon as all pages that have the old code registered and unloaded/closed.

虽然一开始有点难以理解,但如果您关心缓存管理,理解和利用不同的 Service Worker 生命周期状态/事件很重要.如果不是这个更新逻辑,一旦你为给定范围注册了一个 service worker,它就永远不会放弃控制,如果你的代码中有错误/需要添加新功能,你就会被卡住.

While a bit difficult to wrap your head around at first, understanding and making use of the different service worker lifecycle states/events are important if you're concerned about cache management. If it weren't for this update logic, once you registered a service worker for a given scope once, it would never give up control, and you'd be stuck if you had a bug in your code/needed to add new functionality.

这篇关于如何在没有单独 JS 文件的情况下使用 ServiceWorker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆