首页 > 解决方案 > Service Worker 工作箱使请求翻倍

问题描述

我正在尝试将 Service Worker 添加到我的 wordpress 网站。但是当我在后端上传任何媒体时,我得到了 2 个副本。我不知道问题出在哪里。以下是我的服务人员代码。

我认为这是因为后台同步。任何人都可以帮助测试。当我添加到脚本中的任何更改时,我如何使用最近的代码成功测试它?

import { registerRoute, NavigationRoute } from 'workbox-routing';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { CacheFirst, NetworkFirst, NetworkOnly } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { RangeRequestsPlugin } from 'workbox-range-requests';
import { Queue }  from 'workbox-background-sync';
import * as navigationPreload from 'workbox-navigation-preload';

registerRoute(
    ({url}) =>  url.origin === 'https://fonts.googleapis.com' ||
                url.origin === 'http://fonts.googleapis.com' ||
                url.origin === 'https://fonts.gstatic.com',
    new CacheFirst({
        cacheName: 'google-fonts',
        plugins: [
            new ExpirationPlugin({maxEntries: 20}),
        ],
    })
);

registerRoute(
    /\.(?:png|gif|jpg|jpeg|webp|svg|webmanifest)$/,
    new CacheFirst({
        cacheName: 'images',
        plugins: [
            new ExpirationPlugin({
                maxEntries: 60,
                maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
                purgeOnQuotaError: true,
            }),
        ],
    })
);

registerRoute(
    /\.(?:js|css)(\?ver=.*)?$/,
    new CacheFirst({
        cacheName: 'static-resources',
    })
);

registerRoute(
    /(\.webm$|\.mp4$)/,
    new CacheFirst({
        cacheName: 'media',
        plugins: [
            new CacheableResponsePlugin({statuses: [200]}),
            new RangeRequestsPlugin(),
        ],
    })
);

registerRoute(
    ({url}) => url.pathname.startsWith('/wp-admin/') ||
                url.pathname.startsWith('/wp-login/'),
    new NetworkOnly()
);

const bgSyncPlugin = new Queue('offlineQueue1', {
    maxRetentionTime: 24 * 60
});

registerRoute(
    /\/api\/.*\/*.json/,
    new NetworkOnly({
        plugins: [bgSyncPlugin]
    }),
    'POST'
);

/* eslint-disable */
const queue = new Queue('offlineQueue');

self.addEventListener('fetch', (event) => {
    // Clone the request to ensure it's safe to read when
    // adding to the Queue.
    const promiseChain = fetch(event.request.clone()).catch((err) => {
        return queue.pushRequest({request: event.request});
    });

    event.waitUntil(promiseChain);
});
/* eslint-enable */

navigationPreload.enable();

registerRoute(
    new NavigationRoute(
        new NetworkFirst({
            cacheName: 'cached-navigations'
        })
    )
);

标签: wordpresscachingservice-workerworkbox

解决方案


推荐阅读