简体   繁体   中英

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? If files are under my root domain, everything is ok else I get always errors like "cross origin domain...".

All my static resources are on a cdn, how should I handle caching those files?

My code in AMP

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

My service 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);
            })
    );
});

All sample are based on local resources :(

Also how to serve them after? A complete sample will be very helpful, thx.

I found an answer which works in this article 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;
            })
    );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM