【问题标题】:How to use a service worker in AMP files to cache files from a CDN?如何在 AMP 文件中使用 service worker 来缓存 CDN 中的文件?
【发布时间】:2018-02-25 18:10:07
【问题描述】:

我想让服务人员缓存来自我的 cdn 的文件? 如果文件在我的根域下,则一切正常,否则我总是会收到诸如“跨域域...”之类的错误。

我所有的静态资源都在一个 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);
            })
    );
});

所有样本均基于本地资源:(

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

【问题讨论】:

    标签: javascript service-worker amp-html progressive-web-apps


    【解决方案1】:

    我找到了适用于本文的答案 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;
                })
        );
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 1970-01-01
      • 2016-02-23
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2019-10-13
      • 2019-07-17
      相关资源
      最近更新 更多