如何使用 JavaScript 创建离线 Web 应用程序

Rid*_*son 3 html javascript offline web

我正在寻找一个关于如何使用 html、JavaScript 或者 jQuery 创建离线兼容 Web 应用程序的解决方案。我研究了 Service Worker,但它们还无法与所有移动设备相媲美。我还查看了清单文件,它有效,但它没有\xe2\x80\x99t 更新文件。所以现在我\xe2\x80\x99m在这里寻求解决方案。我希望这个应用程序成为一个音乐网站,也可以是一个网络应用程序。我喜欢音乐,我把它带到任何地方,所以我\xe2\x80\x99m试图找出如何保存网站文件以供离线使用,所以即使我没有\xe2\x80\x99t有WiFi,我也可以听我保存的音乐。顺便说一句,我\xe2\x80\x99d喜欢保存的文件是:

\n\n
main.js\nMain.css\nIndex.html\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑 1 \n另外,如果您知道如何正确使用服务工作者,您能举个例子吗?

\n

NVR*_*VRM 6

备查:

\n
\n

1/在应用程序文件夹中创建一个 Service Worker 文件。

\n

例子sw.js

\n
let cacheName = "core" // Whatever name\n// Pass all assets here\n// This example use a folder named \xc2\xab/core\xc2\xbb in the root folder\n// It is mandatory to add an icon (Important for mobile users)\nlet filesToCache = [\n  "/",\n  "/index.html",\n  "/core/app.css",\n  "/core/main.js",\n  "/core/otherlib.js",\n  "/core/favicon.ico"\n]\n\nself.addEventListener("install", function(e) {\n  e.waitUntil(\n    caches.open(cacheName).then(function(cache) {\n      return cache.addAll(filesToCache)\n    })\n  )\n})\n\nself.addEventListener("fetch", function(e) {\n  e.respondWith(\n    caches.match(e.request).then(function(response) {\n      return response || fetch(e.request)\n    })\n  )\n})\n
Run Code Online (Sandbox Code Playgroud)\n
\n

2/在应用程序中的任意位置添加事件:onload

\n
window.onload = () => {\n  "use strict";\n\n  if ("serviceWorker" in navigator && document.URL.split(":")[0] !== "file") {\n    navigator.serviceWorker.register("./sw.js");\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

3/在应用程序文件夹中创建一个文件。manifest.json

\n
{\n    "name": "APP",\n    "short_name": "App",\n    "lang": "en-US",\n    "start_url": "/index.html",\n    "display": "standalone"\n  }\n
Run Code Online (Sandbox Code Playgroud)\n
\n

4/测试

\n

从根文件夹启动 Web 服务器:

\n
php -S localhost:8090\n
Run Code Online (Sandbox Code Playgroud)\n

访问http://localhost:8090一次。

\n

使用 Ctrl + c 停止 Web 服务器。

\n

刷新http://localhost:8090,页面应该有响应。

\n
\n

要在开发时关闭,请删除该onload事件,然后在 Firefox\n中访问about:debugging#workers以注销该服务。

\n
\n
\n

application最新版本的 Firefox直接在调试器中显示选项卡。about:debugging#workers不再有效。

\n

https://developer.mozilla.org/en-US/docs/Tools/Application/Service_workers

\n

来源了解更多详情

\n

Manifest.json 参考

\n