Advanced Cache Optimizer with Service Worker

利用 Service Worker 和 Workbox 实现高效缓存管理,打造“不走味”的缓存体验

// ==UserScript==
// @name         Advanced Cache Optimizer with Service Worker
// @namespace    https://viayoo.com/
// @version      1.0
// @description  利用 Service Worker 和 Workbox 实现高效缓存管理,打造“不走味”的缓存体验
// @match        https://*/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // Service Worker 脚本代码(作为字符串)
    const swCode = `
        importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js');

        if (workbox) {
            console.log('Workbox 加载成功');

            // HTML 页面采用 Network First 策略,保证新鲜度
            workbox.routing.registerRoute(
                ({ request }) => request.destination === 'document',
                new workbox.strategies.NetworkFirst({
                    cacheName: 'html-cache',
                    plugins: [
                        new workbox.expiration.ExpirationPlugin({
                            maxEntries: 50,                // 最多缓存 50 个页面
                            maxAgeSeconds: 24 * 60 * 60,     // 24 小时后过期
                        }),
                    ],
                })
            );

            // JavaScript 和 CSS 文件采用 Stale While Revalidate 策略,快速响应同时后台更新
            workbox.routing.registerRoute(
                ({ request }) => request.destination === 'script' || request.destination === 'style',
                new workbox.strategies.StaleWhileRevalidate({
                    cacheName: 'static-resources',
                    plugins: [
                        new workbox.expiration.ExpirationPlugin({
                            maxEntries: 100,               // 最多缓存 100 个文件
                            maxAgeSeconds: 24 * 60 * 60,     // 24 小时后过期
                        }),
                    ],
                })
            );

            // 图片资源采用 Cache First 策略,实现快速加载
            workbox.routing.registerRoute(
                ({ request }) => request.destination === 'image',
                new workbox.strategies.CacheFirst({
                    cacheName: 'image-cache',
                    plugins: [
                        new workbox.expiration.ExpirationPlugin({
                            maxEntries: 200,               // 最多缓存 200 张图片
                            maxAgeSeconds: 7 * 24 * 60 * 60, // 一周后过期
                        }),
                    ],
                })
            );
        } else {
            console.log('Workbox 加载失败,请检查网络或版本问题');
        }
    `;

    // 创建一个 Blob 对象,包含 Service Worker 代码
    const blob = new Blob([swCode], { type: 'application/javascript' });
    const swUrl = URL.createObjectURL(blob);

    // 注册(不可用) Service Worker
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register(swUrl).then(function(registration) {
            console.log('Service Worker 注册(不可用)成功:', registration);
        }).catch(function(error) {
            console.error('Service Worker 注册(不可用)失败:', error);
        });
    } else {
        console.error('该浏览器不支持 Service Worker');
    }
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址