如果资源位于不同的域上,如何使用 service-worker? [英] How to use service-worker if resources are on different domains?
问题描述
我们知道 service worker 是从项目文件夹的根目录注册的,但是有没有办法从不同的域中获取一些静态资源(css、js)?
As we know service worker is registered from the root of the project folder but, is there any way to fetch some static resources (css, js) from different domain(s)?
示例:
myWebsite.com
//主网址(例如 index.html)abc.com/css/style.css
//css文件路径xyz.com/js/jsFile.js
//javascript文件路径
myWebsite.com
// main url (e.g. index.html)abc.com/css/style.css
// css file pathxyz.com/js/jsFile.js
//javascript file path
推荐答案
任何来自页面的请求(iframe 子资源除外)都将通过 Service Worker.这些资源可以来自相同或不同的来源.您可以缓存这些资源,以便它们可以离线使用,但是作为开发人员,除非资源设置了正确的 CORS 标头,否则您无法操作或检查它们的内容.
Any request that comes from the page (except iframe sub-resources) will pass through the service worker. These resources can be from the same or different origin. You can cache these resources so that they are available offline however as a developer you can't manipulate or inspect the contents of them unless the resources have the correct CORS header set.
例如,在您的安装事件中,您可以缓存不在您的域中的远程文件.
For example, in your install event, you can Cache a remote file that is not on your domain.
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('airhorner').then(function(cache) {
return cache.addAll([
'https://paul.kinlan.me/'
]);
})
);
});
这篇关于如果资源位于不同的域上,如何使用 service-worker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!