我一直在使用 Google Web Starter Kit ( https://github.com/google/web-starter-kit ) 并且有一个小的渐进式 Web 应用程序在工作,但我坚持一件事:从外部 CDN 缓存静态文件。例如。我正在使用 https://fonts.googleapis.com/icon?family=Material+Icons 中的 MDL 图标我看不到缓存请求的方法,因为服务 worker 仅响应我的应用程序域中的 URL。
我看到的选项: 1. 下载文件并将其放在 vendor 文件夹中。优点:易于设置SW缓存。缺点:文件不会随着新图标的添加而保持最新(尽管这并不重要,因为我的代码只会使用可用的图标)。
使用 NPM 存储库:https://www.npmjs.com/package/material-design-icons并使用构建步骤从 node_modules 复制 CSS 文件。优点:将允许从 NPM 自动更新。缺点:设置稍微复杂一些。
一些奇特的代理方法可以让我使用 SW 来缓存外部 URL。例如myapp.com/loadExternal?url= https://fonts.googleapis.com/icon?family=Material+Icons
我现在倾向于 2,但很高兴知道 3 是否可行。
最佳答案
TLDR:尝试选项 3。稍后你会感谢我的。
来自 Google Docs :
默认情况下,如果不支持 CORS,从第三方 URL 获取资源将失败。您可以向请求添加一个 no-CORS
选项来克服这个问题,尽管这会导致“不透明”响应,这意味着您将无法判断响应是否成功。
所以
选项 1
添加no-cors
header
var CACHE_NAME = 'my-site-cache-v1';
var urlsToPrefetch = [
'/',
'/styles/main.css',
'/script/main.js',
'https://fonts.googleapis.com/icon?family=Material+Icons'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
// Magic is here. Look the mode: 'no-cors' part.
cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
return new Request(urlToPrefetch, { mode: 'no-cors' });
})).then(function() {
console.log('All resources have been fetched and cached.');
});
})
);
});
正如OP所说,当资源更新时,在这种情况下很难获得最新的副本。另一个问题是,正如我所说,您不会知道响应是否成功。
选项 2
或者像 OP 所说的那样,我们可以创建一个代理服务器:一些简单的东西(伪代码,未测试,Node Express 代码)
var request = require('request');
app.get('/library', function(req,res) {
// read the param
var thirdPartyUrl = req.query.thirdPartyUrl;
request(thirdPartyUrl).pipe(res);
});
当你转到 /library?thirdPartyUrl=https://fonts.googleapis.com/icon?family=Material+Icons
时应该给你响应并缓存它,就像我们通常缓存我们的响应一样.例如:删除 no-cors
并将 urlsToPrefetch
替换为以下值:
var urlsToPrefetch = [
'/',
'/library?thirdPartyUrl=https://fonts.googleapis.com/icon?family=Material+Icons',
'/library?thirdPartyUrl=https://fonts.googleapis.com/icon?family=Roboto'
];
选项 3
我认为这是最好和更简单的方法。使用工作箱。我们尝试过使用和不使用 workbox 创建 PWA,并且使用 workbox 很简单。
阅读工作箱:https://developers.google.com/web/tools/workbox/
在初始设置后实现这样的路由:
workbox.routing.registerRoute(
new RegExp('^https://third-party.example.com/images/'),
new workbox.strategies.CacheFirst({
cacheName: 'image-cache',
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
})
]
})
);
关于javascript - 如何使用 Service Worker 缓存外部 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39432717/