美文网首页
Service Worker

Service Worker

作者: monvhh | 来源:发表于2018-11-05 22:27 被阅读0次

Service Worker:
应用、浏览器、与network之间的代理。
拦截network请求,用某种策略更新资源。

事件驱动。
是一种worker,所以单独线程,所以不能访问DOM。
完全异步,不能使用同步API。

只能用HTTPS。毕竟做代理,拦截请求,是件危险的事情。

使用大量Promise。

先cache再network


Cache then network
self.addEventListener('fetch', function(e) {
  console.log('[Service Worker] Fetch', e.request.url);
  var dataUrl = 'https://query.yahooapis.com/v1/public/yql';
  if (e.request.url.indexOf(dataUrl) > -1) {
    /*
     * When the request URL contains dataUrl, the app is asking for fresh
     * weather data. In this case, the service worker always goes to the
     * network and then caches the response. This is called the "Cache then
     * network" strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-then-network
     */
    e.respondWith(
      caches.open(dataCacheName).then(function(cache) {
        return fetch(e.request).then(function(response){
          cache.put(e.request.url, response.clone());
          return response;
        });
      })
    );
  } else {
    /*
     * The app is asking for app shell files. In this scenario the app uses the
     * "Cache, falling back to the network" offline strategy:
     * https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network
     */
    e.respondWith(
      caches.match(e.request).then(function(response) {
        return response || fetch(e.request);
      })
    );
  }
});

其他功能暂未研究。

https://developer.mozilla.org/zh-CN/docs/Web/API/Service_Worker_API
https://jakearchibald.com/2014/offline-cookbook/#cache-then-network

相关文章

网友评论

      本文标题:Service Worker

      本文链接:https://www.haomeiwen.com/subject/gmmexqtx.html