gpt4 book ai didi

javascript - 如何让 Workbox PWA 与 .php 文件一起工作

转载 作者:行者123 更新时间:2023-11-30 11:20:55 25 4
gpt4 key购买 nike

我是 PWA 的新手,正在使用 Workbox;所以我有这个具有以下文件结构的测试文件夹,使用 localhost 作为我的服务器 (即 localhost/test)

  1. index.html
  2. 测试.css
  3. 测试.jpg
  4. 测试.js
  5. sw.js(代码如下所示);

    importScripts(' https://storage.googleapis.com/workbox-cdn/releases/3.0.0/workbox-sw.js ');

    if (workbox) {
    console.log(`Yay! Workbox is loaded 🎉`);
    } else {
    console.log(`Boo! Workbox didn't load 😬`);
    }

    //precache all the site files
    workbox.precaching.precacheAndRoute([
    {
    "url": "index.html",
    "revision": "8e0llff09b765727bf6ae49ccbe60"
    },
    {
    "url": "test.css",
    "revision": "1fe106d7b2bedfd2dda77f06479fb676"
    },
    {
    "url": "test.jpg",
    "revision": "1afdsoaigyusga6d9a07sd9gsa867dgs"
    },
    {
    "url": "test.js",
    "revision": "8asdufosdf89ausdf8ausdfasdf98afd"
    }

    ]);

一切正常,文件已预缓存,当我处于离线模式时,我没有收到此常规离线消息,如下图所示。

enter image description here

因此,我复制了包含 test-2 文件夹的确切文件夹,然后将我的 index.html 文件 重命名为 index.php 并在我的 sw .js 文件 我将 url 更新为以下代码

{
"url": "index.php",
"revision": "8e987fasd5727bf6ae49ccbe60"
},

- 请注意,我也更改了修订值

我这样做是因为我想使用 Workbox 将 PWA 实现到我自己定制的单页应用程序中(但它是 .php 格式)。

来到我的浏览器运行 localhost/test-2 (正常模式),我的文件也被预缓存,包括我的 index.php 文件 (我的控制台中没有错误消息,Service Worker 工作得很好);仅供我在源选项卡中切换到(离线模式) 并刷新浏览器以测试离线体验,唉!我收到了这条离线消息,如下图所示:(

enter image description here

我不知道出了什么问题,我不知道发生了什么,几天来我试图用谷歌搜索一些原因,但我似乎没有得到任何正确和相应的答案。大多数教程都带有 .html

所以问题是我如何使用 .php 文件实现 PWA,以便当用户离线时,他们不会收到正常的“您已离线”消息,而是应该呈现我的网页?

提前致谢

最佳答案

详细说明@pate 的回答。

默认情况下,Workbox 会尝试确保开箱即用地支持漂亮的 URL。

所以在第一个例子中,你缓存了/test/index.html。因此,当您请求 /test/ 时,Workbox 预缓存实际上会检查预缓存:

  • /测试/
  • /test/index.html

如果您的页面是 /test/about.html,并且您访问了页面 /test/about,预缓存将附加一个 .html 并检查它。

当你切换到 .php 扩展时,这个逻辑突然就不再有效了。

有几个选项可以让这个工作:

  1. 如果您正在使用任何工作箱工具来构建您的 list ,您将使用 templatedUrls 功能映射到一个文件 (More details here):

    templatedUrls: {
    '/test-2/': ['/test-2/index.php']
    }
  2. 如果您自己在服务器端制作预缓存列表,您可以告诉它预缓存 URL /test-2/ 而没有 index.php,预缓存只会缓存它。 请注意,您必须确保修订版随对 index.php 的任何更改而更改

  3. 如果您没有制作预缓存 list ,您可以使用 urlManipulaion 选项告诉预缓存检查 URL,( More details here ):

    workbox.precaching.precacheAndRoute(
    [
    .....
    ],
    {
    urlManipulaion: ({url}) => {
    // TODO: Check if the URL ends in slash or not
    // Add index.php based on this.
    return [url, `${url}.php`, `${url}index.php`];
    }
    }
    );

关于javascript - 如何让 Workbox PWA 与 .php 文件一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49855907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com