为什么我的 Workbox GenerateSW 在连接时显示我的离线页面?

Why is my Workbox GenerateSW showing my offline page while connected?

我正在尝试使用 Workbox GenerateSW() 和 运行ning 设置我的离线页面,但在我清除站点数据和硬刷新后第一次加载时显示我的主页,但在后续加载时出现问题我正在获取我设置的离线页面,即使我在线。我有一个多页面 PHP 应用程序,其中包含由 CDN 提供的资产。我 运行 由 npm 节点脚本调用的 JS 文件中的 GenerateSW() 任务。

这是我的 GenerateSW() 代码...

// Pull in .env file values...
const dotEnv = require('dotenv').config({ path: '/var/www/my-project/sites/www/.env' });
if (dotEnv.error) {
  throw dotEnv.error
}

const {generateSW} = require('workbox-build');

// Used to break cache on generate of new SW where file is composed of multiple pieces that can't be watched.
const genRanHex = (size = 24) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

const mode = 'development';

generateSW({
    swDest: './sites/www/public/service-worker.js',
    skipWaiting: true,
    clientsClaim: true,
    cleanupOutdatedCaches: true,
    cacheId: genRanHex(),
    mode: mode,
    navigateFallback: '/offline',
    offlineGoogleAnalytics: mode === 'production',
    globDirectory: './sites/assets/public',
    globPatterns: [
        'img/shell/**/*.{svg,png}',
        'dist/**/*.{js,css}',
        'manifest.json'
    ],
    modifyURLPrefix: {
        'dist/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/dist/`,
        'img/shell/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/img/shell/`,
    },
    ignoreURLParametersMatching: [/v/],
    additionalManifestEntries: [
        {
            "url": "/offline",
            "revision": genRanHex()
        }
    ],
    runtimeCaching: []
}).then(({count, size}) => {
    console.log(`Generated service worker, which will precache ${count} files, totaling ${size} bytes.`);
}).catch(console.error);

navigateFallback实际上不是离线页面。来自 workbox docs:

If specified, all navigation requests for URLs that aren't precached will be fulfilled with the HTML at the URL provided. You must pass in the URL of an HTML document that is listed in your precache manifest. This is meant to be used in a Single Page App scenario, in which you want all navigations to use common App Shell HTML.

对于离线页面, 可能会有所帮助。

所以在我滥用 navigateFallback 时接受的答案是正确的,我试图将其用作非缓存路由的离线回退。经过一些挖掘和修补,我找到了正确的方法。我在 Workbox 上遗漏或没有充分记录的重要部分是离线回退发生在 runtimeCache 级别...

// Pull in .env file values...
const dotEnv = require('dotenv').config({ path: '/var/www/my-project/sites/www/.env' });
if (dotEnv.error) {
  throw dotEnv.error
}

const {generateSW} = require('workbox-build');

// Used to break cache on generate of new SW where file is composed of multiple pieces that can't be watched.
const genRanHex = (size = 24) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

const mode = 'development';

generateSW({
    swDest: './sites/www/public/service-worker.js',
    skipWaiting: true,
    clientsClaim: true,
    cleanupOutdatedCaches: true,
    cacheId: genRanHex(),
    mode: mode,
    offlineGoogleAnalytics: mode === 'production',
    globDirectory: './sites/assets/public',
    globPatterns: [
        'img/shell/**/*.{svg,png}',
        'dist/**/*.{js,css}',
        'manifest.json'
    ],
    modifyURLPrefix: {
        'dist/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/dist/`,
        'img/shell/': `${dotEnv.parsed.APPLICATION_ASSETS_CDN}/img/shell/`,
    },
    ignoreURLParametersMatching: [/v/],
    additionalManifestEntries: [
        {
            "url": "/offline",
            "revision": genRanHex()
        }
    ],
    runtimeCaching: [
        {
        urlPattern: /^https:\/\/([\w+\.\-]+www\.mysite\.tv)(|\/.*)$/,
        handler: 'StaleWhileRevalidate',
        options: {
            cacheName: 'core',
            precacheFallback: {
                fallbackURL: '/offline' // THIS IS THE KEY
            }
        }
    }
]
}).then(({count, size}) => {
    console.log(`Generated service worker, which will precache ${count} files, totaling ${size} bytes.`);
}).catch(console.error);