javascript 应用_如何利用JavaScript的功能使您的应用脱机工作

javascript 应用

In today’s world, connectivity has made us more mobile than ever which (paradoxically) cause us to be offline sometimes: when we’re in airplane mode, have a bad connection, have no more data, are on the subway…and so on.

在当今世界,连通性使我们比以往任何时候都更具移动性,这(有时很奇怪)使我们有时下线了:当我们处于飞行模式,连接不良,没有更多数据,正在地铁上时,等等。

A second effect of this mobility is the slow loading of heavy websites: Amazon found that just 100 milliseconds of extra load time cost them 1% of sales.

这种移动性的第二个影响是繁重的网站加载速度慢:亚马逊发现,仅100毫秒的额外加载时间使他们损失了1%的销售收入

In these situations, we would like to have offline access to our content. That’s why tools like Instapaper and Pocket exist. Spotify and Netflix also allow you to download media for offline use.

在这种情况下,我们希望可以离线访问我们的内容。 这就是为什么存在InstapaperPocket之类的工具的原因。 SpotifyNetflix还允许您下载媒体以供离线使用。

We can easily see there is a demand for this feature and how it can benefit your business.

我们可以很容易地看到对此功能的需求以及它如何使您的业务受益。

It is time for the web to go offline.

现在是时候让网络离线。

Luckily we don’t need to build native apps to achieve this goal anymore. We can create an offline website with the power of JavaScript thanks to the new service workers and Cache API features.

幸运的是,我们不再需要构建本机应用程序来实现此目标。 借助新的服务工作者Cache API功能,我们可以使用JavaScript的功能创建一个脱机网站。

什么是服务人员(SW)? (What is a service Worker (SW)?)

Service workers are JavaScript code that runs in the background of your website, even when the page is closed. For offline uses, one of their goals is to store network requests or images in the browser cache.

服务工作者是即使在关闭页面后仍在网站后台运行JavaScript代码。 对于离线使用,他们的目标之一是将网络请求或图像存储在浏览器缓存中。

The agency BETC made a demo website called whentheinternetisdown.com for the french telecom company Bouygues. It only works offline and feels kind of magical. Go try it out :)

BETC代理机构为法国电信公司Bouygues创建了一个名为whentheinternetisdown.com的演示网站。 它只能在离线状态下使用,感觉有点神奇。 去试试看:)

It’s the caching that makes the magic of the site: you can come back in 3 weeks, 1 month, 1 year, still without a connection, and access all the content. — Maxime Huygue, Head of BETC Digital Studio

缓存使网站变得神奇:您可以在3周,1个月,1年的时间内无连接地返回,并访问所有内容。 — BETC Digital Studio负责人Maxime Huygue

Ok this is cool, tell me how to do it then.

好的,这很酷,然后告诉我该怎么做。

Ok, let’s begin with some prerequisites:

好的,让我们从一些先决条件开始:

  • In order to use SWs, you must enable https on your website.

    为了使用软件,必须在网站上启用https。
  • You should have decent comprehension of how JavaScript promises work.

    您应该对JavaScript Promise的工作方式有一定的了解。

  • SWs works in all modern browsers except our friend IE.

    除我们的朋友IE外,SW均可在所有现代浏览器中使用。

  • Even if it’s JavaScript, they run in the context of web workers. Which means: no DOM, and run outside of the main thread.

    即使是JavaScript,它们也可以在Web worker的上下文中运行。 这意味着:没有DOM,并且在主线程之外运行。

  • Understand how databases operate.

    了解数据库如何运行。
  • The code of your service worker needs to be in a separate JavaScript file. Example: service-worker.js

    您的服务人员的代码需要在单独JavaScript文件中。 示例:service-worker.js

服务人员生命周期 (Service workers lifecycle)

To be able to work, SWs must be registered within your application, then installed. You should check if SWs are compatible with your client before doing so.

为了能够工作,软件必须在您的应用程序中注册,然后安装。 在这样做之前,您应该检查软件是否与您的客户端兼容。

1)注册 (1) Registration)

If available, register your SW file. It will return a promise, so you can handle errors. You can also specify a scope of urls in the registration options.

如果可用,请注册您的SW文件。 它将返回一个承诺,因此您可以处理错误。 您还可以在注册选项中指定网址范围。

2)安装 (2) Installation)

Service workers are event-based. Briefly, you have to attach callbacks to events, as you would do with an element.addEventListener. The first event you need to use is the install event. This is a good time to cache all your vital resources as Javascript, CSS, HTML, Images… This is where the Cache API joins the party!

服务人员是基于事件的。 简而言之,您必须像对element.addEventListener那样将回调附加到事件上。 您需要使用的第一个事件是install事件。 这是缓存所有重要资源(如Javascript,CSS,HTML,图像)的好时机……这是Cache API参加聚会的地方!

Then open the method or create a cache linked to a desired name. The returned promise needs to be wrapped into event.waitUntil(), which will delay the installation of the service worker until the promise is resolved. Otherwise, the install event fails and the service worker will be discarded.

然后打开方法或创建链接到所需名称的缓存。 需要将返回的承诺包装到event.waitUntil()中,这将延迟服务工作程序的安装,直到解决承诺为止。 否则,安装事件将失败,服务工作者将被丢弃。

Please be cautious with caching: your user’s storage is precious, so don’t abuse it. Also, be careful: the install event can only be called once, and you’ll need to update your SW to modify it.

请注意缓存:用户的存储空间非常宝贵,因此请不要滥用它。 另外,请注意:install事件只能被调用一次,并且您需要更新SW以对其进行修改。

3)激活 (3) Activation)

This one is a bit subtle.

这个有点微妙。

Once the installation has completed, the service worker isn’t active yet: we are in the installed state.

安装完成后,服务工作者尚未激活:我们处于已安装状态。

In this state, it waits to take control of the page. It then moves on to the next phase in the lifecycle, which is the activation phase.

在这种状态下,它等待控制页面。 然后,它进入生命周期的下一个阶段,即激活阶段。

The activation phase is handy when you update a SW. The most common case is to clear the cache of the previous SW installed.

更新软件时,激活阶段很方便。 最常见的情况是清除先前安装的软件的缓存。

Please note that, once successfully installed, the updated worker will wait until the existing worker is controlling zero clients (clients overlap during a refresh).

请注意,成功安装后,更新的工作程序将等待,直到现有工作程序控制零客户端(刷新期间客户端重叠)。

self.skipWaiting() prevents the waiting, meaning the service worker activates as soon as it’s finished installing. The advantage of this method is that you can receive fetch events faster.

self.skipWaiting()避免了等待,这意味着服务工作者在完成安装后立即激活。 这种方法的优点是您可以更快地接收提取事件。

It doesn’t really matter when you call skipWaiting(), as long as it’s during or before waiting. It’s pretty common to call it in the install event.

何时调用skipWaiting()并不重要,只要它在等待期间或等待之前即可。 在install事件中调用它是很常见的。

Phew! Let’s take a break and sum up what we’ve seen:

让我们休息一下,总结一下我们所看到的:

  • Service workers are pieces of JavaScript that enable offline features such as caching.

    服务工作者是启用离线功能(例如缓存)JavaScript片段。
  • We explored the SW Lifecycle: registration, installation, activation

    我们探索了软件生命周期:注册,安装,激活
  • We learned how to implement common uses cases such as: caching resources and clearing caches with the Cache API.

    我们学习了如何实现常见用例,例如:使用Cache API缓存资源和清除缓存。
  • We saw that self.skipWaiting and self.clients.claim allow us to activate SWs faster in order to catch events faster.

    我们看到self.skipWaiting和self.clients.claim允许我们更快地激活软件,以便更快地捕获事件。

Ok moving right along…

确定继续前进...

4)提取 (4) Fetch)

The fetch event allows us to intercept network requests and store responses or customize them.

fetch事件使我们能够拦截网络请求并存储响应或自定义它们。

The main advantage of this hook is to return the cached resources instead of making a request call. You should take a look at the Fetch API for handling your request calls.

该挂钩的主要优点是返回缓存的资源,而不是发出请求调用。 您应该查看用于处理请求调用的Fetch API

We can’t cover all the possibilities offered by service workers in one article. Still, I encourage you to look into what’s possible: Custom 404, Background Sync API for offline analytics, ServiceWorker-side templating…. the future looks exciting!

我们无法在一篇文章中介绍服务人员提供的所有可能性。 尽管如此,我还是鼓励您研究一下可能的方法: 自定义404用于离线分析的Background Sync APIServiceWorker端模板 ...。 未来看起来令人兴奋!

So far we’ve seen what a service worker is, how it works through its lifecycle, and the most common use cases by playing with Cache and Fetch API. Those two APIs give us a whole new way of managing URL addressable resources in the browser. To complete this guide, let see how we can store other types of data, for example a user’s JSON from your database.

到目前为止,我们已经了解了服务工作者是什么,如何在其生命周期中工作,以及通过使用Cache和Fetch API来了解最常见的用例。 这两个API为我们提供了一种在浏览器中管理URL可寻址资源的全新方法。 为了完成本指南,让我们看看如何存储其他类型的数据,例如数据库中用户的JSON

使用IndexedDB存储自定义数据 (Store custom data with IndexedDB)

A general guideline for data storage is that URL addressable resources should be stored with the Cache interface, and other data should be stored with IndexedDB. For example HTML, CSS, and JS files should be stored in the cache, while JSON data should be stored in IndexedDB. Note that this is only a guideline, not a firm rule. (source)

数据存储的一般准则是URL可寻址资源应使用Cache接口存储,而其他数据应使用IndexedDB存储。 例如,HTML,CSS和JS文件应存储在缓存中,而JSON数据应存储在IndexedDB中。 请注意,这只是一个准则,而不是严格的规则。 ( 来源 )

In short, we will see when you shouldn’t use Cache API but IndexedDB instead. Both are asynchronous and accessible in service workers, web workers, and the window interface . The good news is that it is well supported, even in recent versions of IE.

简而言之,我们将看到何时不应该使用Cache API,应该使用 IndexedDB 。 两者都是异步的,可以在Service Worker,Web Worker和Window Interface中访问 。 好消息是,即使在最新版本的IE中, 它也受到很好的支持

IndexedDB is a NoSQL database. IndexedDB data are stored as key-value pairs in object stores rather than tables. A single database can contain any number of object stores. Whenever a value is stored in an object store, it is associated with a key. It looks like this:

IndexedDB是NoSQL数据库。 IndexedDB数据作为键值对存储对象存储中,而不是表中。 单个数据库可以包含任意数量的对象库。 每当值存储在对象存储中时,它就会与键相关联。 看起来像这样:

Pretty classic, right? The main thing to understand is the concept of key path. It tells the browser which key to use to extract data from in the object store or index.

很经典吧? 要了解的主要是关键路径的概念。 它告诉浏览器使用哪个键从对象存储或索引中提取数据。

In this example, we can see that our key path is the property id, and it is defined in line 10. Then we return all the items from the database. This is a very basic use case, so if you want to learn more about how IndexedDB works, I advise you to read this excellent article.

在这个例子中,我们可以看到我们的关键路径是属性id,它是在第10行中定义的。然后,我们从数据库中返回所有项目。 这是一个非常基本的用例,因此,如果您想了解有关IndexedDB如何工作的更多信息,建议您阅读这篇出色的文章

结论 (Conclusion)

Taking advantage of the offline web is great for the user experience, and some companies have started to take loot at it. It mostly relies on service workers, JavaScript scripts that run in the background of your website.

利用脱机网络对用户体验非常有用,并且一些公司已经开始对其进行抢劫。 它主要依赖于服务工作者,即在网站后台运行JavaScript脚本。

We’ve seen how to use them trough the service worker lifecycle and what you can do by using the Cache and Fetch API. The possibilities are almost limitless. so be creative and not too greedy on the device storage.

我们已经了解了如何在服务工作者生命周期中使用它们,以及通过使用缓存和提取API可以做什么。 可能性几乎是无限的。 因此要有创造力,不要对设备存储空间过于贪婪。

You can even use databases offline: that what’s IndexedDB is made for. These offline capabilities certainly are part of the future of the web, so it plays well with the new type of websites that Google are creating: Progressive Web Apps.

您甚至可以脱机使用数据库:那是为IndexedDB做的。 这些脱机功能无疑是网络未来的一部分,因此,它可以与Google创建的新型网站:渐进式Web应用程序很好地配合使用。

进一步阅读: (Further reading:)

翻译自: https://www.freecodecamp.org/news/how-to-make-your-app-work-offline-with-the-power-of-javascript-685d968bcfbb/

javascript 应用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值