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

时间:2017-07-05 13:52:48

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

我在我的网站上使用了材料图标和roboto字体,并且我一直在尝试使用sw-precache runtimeCaching API来缓存它,但它不起作用,我不确定我是不是&我#39;做得对。我需要我的服务工作者从缓存中获取这些文件。这是我的代码。我将它整合到我的gulp任务中:

fidiv 2

我试图缓存这些链接:

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

1 个答案:

答案 0 :(得分:1)

这是我的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);

});