javascript - 如何使用 sw-precache runtimeCaching 缓存 googleapis.com

标签 javascript caching service-worker sw-precache sw-toolbox

我在我的网站上使用了 Material 图标和 roboto 字体,并且我一直在尝试使用 sw-precache runtimeCaching API 来缓存它,但它不起作用,我不确定我是否做得对。我需要我的服务人员从缓存中获取这些文件。这是我的代码。我将它集成到我的 gulp 任务中:

gulp.task('create-sw', ['watchCss', 'watchJS'], callback => {
    preCache.write(path.join('.', 'sw.js'), {
        runtimeCaching: [{
            urlPattern: /^https:\/\/fonts\.googleapis\.com$/,
            handler: 'cacheFirst',
            options: {
                cache: {
                    maxEntries: 10,
                    name: 'google-apis'
            }
        },
    }],
        staticFileGlobs: [
            './script.js',
            './manifest.json',
            './app/**/*.{html,json}',
            './dist/**/*.{js,css,eot,ttf,woff,woff2}',
            './**/*.{png,jpeg,jpg,svg,gif}',
            './index.html',
        ],
        stripPrefix: '.',
        maximumFileSizeToCacheInBytes: 15000000,
    }, callback)
});

我正在尝试缓存这些链接:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&amp;lang=en">

最佳答案

这是我的 GULP 任务,它为 Instagram 图像生成缓存:

gulp.task('generate-service-worker', function(callback) {
var swPrecache = require('sw-precache');
var rootDir = 'app';

swPrecache.write(`${rootDir}/service-worker.js`, {
    staticFileGlobs: [rootDir + '/**/*.{php,js,html,css,png,jpg,gif,svg,eot,ttf,woff,json}', './'],
    stripPrefix: rootDir,
    directoryIndex: false,
    maximumFileSizeToCacheInBytes: 10097152,
    runtimeCaching: [{
        urlPattern: /^https:\/\/scontent\.cdninstagram\.com/,
        handler: 'networkFirst',
        options: {
            cache: {
                maxEntries: 50,
                name: 'instagram-images-cache'
            }
        }
    }]
}, callback);

});

关于javascript - 如何使用 sw-precache runtimeCaching 缓存 googleapis.com,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44928222/

相关文章:

javascript - 如何实现 AJAX 响应的缓存?就像在 Internet Explorer 中一样

java - 整数包装对象仅在值 127 内共享相同的实例?

ios - 究竟什么时候从 urlcache 的内存和磁盘中删除内容?

javascript - 在 IE 中取消注册(特定)serviceworker 失败,而代码在 Chrome 中正常

javascript - Firefox 类型错误 : ServiceWorker script encountered an error during installation

javascript - Chrome 没有在我的 PWA 中显示 "add to homescreen"

javascript - 将逻辑导出为ex​​press.js 中的函数

javascript - File.dataDirectory 在 Ionic 2 中不起作用

javascript - 在 javascript 中迭代项目的最佳方法是什么?

node.js - ServiceWorker 注册失败 : A bad HTTP response code (404) was received when fetching the script