gpt4 book ai didi

javascript - 如何在 AMP 文件中使用服务 worker 来缓存来自 CDN 的文件?

转载 作者:行者123 更新时间:2023-11-29 11:00:01 33 4
gpt4 key购买 nike

我想要一个 service worker 来缓存来 self 的 cdn 的文件?如果文件在我的根域下,则一切正常,否则我总是会收到诸如“跨源域...”之类的错误。

我所有的静态资源都在 cdn 上,我应该如何处理这些文件的缓存?

我在 AMP 中的代码

<amp-install-serviceworker src="https://www.example.com/swAmp.js" layout="nodisplay"></amp-install-serviceworker>

我的服务 worker swAmp.js

var CACHE_NAME = 'example-v0';
var urls = [
'https://static.example.com/img/menu/1.png',
'https://static.example.com/img/menu/2.png',
'https://static.example.com/img/menu/3.png'
];

self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urls);
})
);
});

所有示例均基于本地资源:(

还有如何服务他们?一个完整的示例将非常有帮助,谢谢。

最佳答案

我在这篇文章中找到了有效的答案 https://filipbech.github.io/2017/02/service-worker-and-caching-from-other-origins

self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE)
.then(function(cache) {
console.log('Opened cache');
urls.forEach(function(value) {
const request = new Request(value, {mode: 'no-cors'});
fetch(request).then(response => cache.put(request, response));
});
return cache;
})
);
});

关于javascript - 如何在 AMP 文件中使用服务 worker 来缓存来自 CDN 的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48976762/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com