首页 > 解决方案 > Why service-worker does not cache js file

问题描述

SW caches an image file, but not JS (size 0 bytes)

    /*serviceWorker*/
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker
            .register('service-worker.js', { scope: '/' })
            .then(function(registration) {
                console.log("Service Worker Registered");
            })
            .catch(function(err) {
                console.log("Service Worker Failed to Register", err);
            })

    };

    const CACHE = 'cache-only-v1';
    const timeout = 400;

    self.addEventListener('install', (event) => {
        event.waitUntil(
        caches.open(CACHE).then((cache) => {
            return cache.addAll([
                '/sys/Raycaster/3d.js',
                '/sys/js/popmotion.global.min.js',
                '/sys/js/anime.min.js',
                'sys/b/bgFeedback.jpg',
                '/sys/b/ic.svg',
                '/sys/b/ani/img_ani_1.webp',
                '/sys/b/ani/img_ani_2.webp',
                '/sys/b/ani/img_ani_3.webp',
                '/sys/printProd/p.webp',
                '/sys/printProd/p2.webp',
                '/sys/printProd/p3.webp',
                '/sys/printProd/p4.webp',
                '/sys/printProd/p5.webp',
                '/sys/printProd/p6.webp',
                '/sys/printProd/p7.webp',
                '/sys/printProd/p8.webp',
                '/sys/printProd/p9.webp',
                '/sys/printProd/p10.webp',
                '/sys/printProd/p11.webp',
                '/sys/printProd/p12.webp',
                '/sys/sliderInSlider/01_el.webp',
                '/sys/sliderInSlider/02_dv.webp',
                '/sys/sliderInSlider/05_snth.webp',
                '/sys/sliderInSlider/06_ton.webp',
                '/sys/sliderInSlider/07_pty.webp',
                '/sys/sliderInSlider/08_lyu.webp',
                '/sys/sliderInSlider/09_kar.webp'
                ]);
            })
        );
    });

Image here: https://f.usemind.org/img/2019-05-28_143451.jpg

标签: service-worker

解决方案


chrome DevTools 中显示的信息是基于Response Headers有时不反映现实的。您的 js 文件已被缓存,但Content-Lenght它的Headers.

要测试它,你可以这样做:

caches.open(CACHES)
.then( cache => cache.match('/sys/js/popmotion.global.min.js'))
.then( res =>res.text())
.then( js => console.log(js))

此代码将检查您的缓存中是否存在 popmotion.global.min.js,并显示其内容。


推荐阅读