如何使用javascript创建离线网络应用 [英] how to create an offline web app using javascript

查看:65
本文介绍了如何使用javascript创建离线网络应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关如何使用html,JavaScript以及jQuery创建离线兼容的Web应用程序的解决方案.我调查了服务人员,但还不能与所有移动设备相提并论.我还查看了清单文件,它可以工作,但是没有更新文件.所以现在我在这里寻求解决方案.我打算将此应用程序作为一个音乐网站,可以将其作为网络应用程序.我喜欢音乐,无处不在,所以我试图找出如何保存网站文件以供离线使用的方法,因此即使没有WiFi,我也可以收听保存的音乐.我要保存的 btw 文件是:

I am looking for a solution on how to create an offline compatible web app using html, JavaScript, and maybe jQuery. I looked into service workers, but they aren’t comparable with all mobile devices yet. I also looked at the manifest file thing, it worked but it didn’t update the files. So now I’m here asking for a solution. I intend this application to be a music website that can be a web app. I like music and i take it everywhere so I’m trying to find out how i can save the website files for offline use so even if I don’t have WiFi, i can listen to my saved music. btw the files I’d like to save are:

main.js
Main.css
Index.html

编辑1 另外,如果您知道如何正确使用服务人员,可以举个例子吗?

EDIT 1 Also, if you know how to properly use service workers, can you show an example?

推荐答案

对于未来参考:

1/在应用程序的 root 文件夹中创建服务工作者文件.

1/ Create a service worker file in the app root folder.

示例 sw.js :

let cacheName = "core" // Whatever name
// Pass all assets here, this example use the root folder «core»
let filesToCache = [
  "/",
  "/index.html",
  "/core/app.css",
  "/core/main.js",
  "/core/otherlib.js",
  "/core/favicon.ico"
]

self.addEventListener("install", function(e) {
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.addAll(filesToCache)
    })
  )
})

self.addEventListener("fetch", function(e) {
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request)
    })
  )
})

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

2/ Add an onload event anywhere in the app:

window.onload = () => {
  "use strict";

  if ("serviceWorker" in navigator && document.URL.split(":")[0] !== "file") {
    navigator.serviceWorker.register("./sw.js");
  }
}

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

3/ Create a manifest.json file in the app root folder.

{
    "name": "APP",
    "short_name": "App",
    "lang": "en-US",
    "start_url": "/index.html",
    "display": "standalone"
  }

4/测试示例.从 root 文件夹启动Web服务器:

4/ Test example. Start a web server from the root folder:

php -S localhost:8090

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

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

Stop the web server with Ctrl + c.

刷新 http://localhost:8090 ,页面应响应.

要在开发时关闭,请删除onload事件,然后在Firefox中访问 about:debugging#workers 取消注册服务.

To switch off when developing, remove the onload event, and in Firefox visit about:debugging#workers to unregister the service.

更多信息来源

Manifest.json参考

这篇关于如何使用javascript创建离线网络应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆