Maison > interface Web > js tutoriel > le corps du texte

JavaScript新知:service workers

阿神
Libérer: 2017-01-24 14:30:41
original
1299 Les gens l'ont consulté

前端技术正在像桌面技术靠近,其中一项很重要的就是就是service workers,它让HTML App离线工作成为可能。本文会以一个简单的案例代码来说明这项技术。我使用的工具:

1.浏览器版本为chrome 55

2.服务器系统:Node 5.0

我们需要准备3个文件:

touch  index.html b.html sw.js
Copier après la connexion

其中文件index.html内容为:

  <script>
    if (&#39;serviceWorker&#39; in navigator) {
      navigator.serviceWorker.register(&#39;/sw.js&#39;);
    }    </script>
Copier après la connexion

它注册一个service worker,文件名为sw.js,一个JavaScript代码文件。所以真正关键的文件是sw.js,其内容为:

   const cacheName = &#39;v1::static&#39;;    self.addEventListener(&#39;install&#39;, e => {
      e.waitUntil(
        caches.open(cacheName).then(cache => {          return cache.addAll([            &#39;/&#39;,
          ]).then(() => self.skipWaiting());
        })
      );
    });    self.addEventListener(&#39;fetch&#39;, event => {
      event.respondWith(
        caches.open(cacheName).then(cache => {          return cache.match(event.request).then(res => {            return res || fetch(event.request)
          });
        })
      );
    });
Copier après la connexion

作为一个事件,install会在ServiceWorker第一次装入时被调用,此处你可以做一些初始化的工作,典型的工作是加载在离线时会需要的文件到cache内。这里我们制定了"/",因此任何内容都会被缓存下来。

第二个事件是fetch,当访问远程资源时会被调用。这里可以做一个匹配,如果在cache内有就曲cache内的资源返回,否则去远程取。

第三个文件b.html就是一个为了演示离线效果的文件,内容为:

<h1>serviceWorker B</h1>
Copier après la connexion

虽然即可安装http server,并在当前路径内执行它:

npm i http-server 
    http-server
Copier après la connexion

访问:

http://localhost:8080/index.html
Copier après la connexion

http://localhost:8080/b.html
Copier après la connexion

随后,关闭http server,再次访问

 http://localhost:8080/b.html
Copier après la connexion

居然可以访问~,而这就是离线实现的效果。

嗯,想要查看service workers的运行状况,还可以使用如下url来:

 chrome://inspect/#service-workers
Copier après la connexion

可以看到更加细节的是这个:

 chrome://serviceworker-internals/
Copier après la connexion

在这里可以启动,撤销注册等操作。

可以查询它的实现情况,还不是那么乐观:

http://caniuse.com/#feat=serviceworkers
Copier après la connexion
Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!