简体   繁体   English

如何在AMP文件中使用服务工作者来缓存CDN中的文件?

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

I would like to a service worker to cache files coming from my cdn? 我想服务工作者缓存来自我的cdn的文件? If files are under my root domain, everything is ok else I get always errors like "cross origin domain...". 如果文件在我的根域下,一切都没问题,否则我总会得到像“cross origin domain ...”这样的错误。

All my static resources are on a cdn, how should I handle caching those files? 我的所有静态资源都在cdn上,我应该如何处理缓存这些文件?

My code in AMP 我的AMP代码

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

My service worker swAmp.js 我的服务人员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);
            })
    );
});

All sample are based on local resources :( 所有样品均基于当地资源:(

Also how to serve them after? 又如何服务他们? A complete sample will be very helpful, thx. thx,完整的样本将非常有用。

I found an answer which works in this article https://filipbech.github.io/2017/02/service-worker-and-caching-from-other-origins 我找到了一个在本文中有效的答案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