簡體   English   中英

如何在AMP文件中使用服務工作者來緩存CDN中的文件?

[英]How to use a service worker in AMP files to cache files from a CDN?

我想服務工作者緩存來自我的cdn的文件? 如果文件在我的根域下,一切都沒問題,否則我總會得到像“cross origin domain ...”這樣的錯誤。

我的所有靜態資源都在cdn上,我應該如何處理緩存這些文件?

我的AMP代碼

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

我的服務人員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);
            })
    );
});

所有樣品均基於當地資源:(

又如何服務他們? thx,完整的樣本將非常有用。

我找到了一個在本文中有效的答案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;
            })
    );
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM