代码之家  ›  专栏  ›  技术社区  ›  Aaron Stein

服务工作者发送两个请求

  •  3
  • Aaron Stein  · 技术社区  · 6 年前

    我实现了一个服务工作者,它缓存所有离线使用的请求,这很好。但是每次我加载一个页面时,有两个请求访问我的Web服务器(一个来自服务工作者,另一个来自浏览器)!

    如何缓存请求并只加载一次页面?

    服务工人.js

    self.addEventListener('install', function(event) {
      //load error page which will show if user has no internet
      var errorPage = new Request('/?p=error&offline');
      event.waitUntil(pushToCache(errorPage));
    });
    
    //If any fetch fails, it will look for the request in the cache and serve it from there first
    self.addEventListener('fetch', function(event) {
      event.waitUntil(pushToCache(event.request));
    
      event.respondWith(
        fetch(event.request) //try loading from internet
        .catch(function (error) {
          return fetchFromCache(event.request);
        }) //no internet connection try getting it from cache
      );
    });
    
    function pushToCache(request){
      if(request.method == "GET"){
        return caches.open('stm-app').then(function (cache) {
          return fetch(request).then(function (response) {
            return cache.put(request, response);
          });
        });
      }
    };
    
    function fetchFromCache(request) {
      return caches.open('stm-app').then(function (cache) {
        return cache.match(request).then(function (matching) {
          if(!matching || matching.status == 404){
            return fetchFromCache(new Request('/?p=error&offline')); //show page that user is offline
          }else{
            return matching;
          }
        });
      });
    }
    

    sw-寄存器.js

    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
      .then(function(registration) {
        console.log('Registered:', registration);
      })
      .catch(function(error) {
        console.log('Registration failed: ', error);
      });
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Konstantinos Kamaropoulos    6 年前

    所以每当你提出请求时,会发生以下情况:

    1. 网页向服务器发送一个获取请求,
    2. 服务工作人员在“fetch”事件上截获请求,
    3. pushToCache() 向服务器激发提取请求 为了缓存响应,
    4. 那么你呢 通过对服务器的提取请求响应事件 它将返回对Web服务器响应的承诺。

    是的,这是有道理的,这件事只是发送了两个请求两个服务器对页面最初提出的每个请求。

    您可能需要考虑的一件事是,首先从缓存响应,然后在网络上获取最新的数据。这样,您就可以避免在出现连接问题的情况下延迟加载,即使用户在线,也可以加快页面的加载时间。

    让我们考虑以下场景:用户或服务器处于脱机状态。一旦您启动了请求,它将不得不超时,然后才能执行捕获部分的承诺并获得缓存的响应。

    截获事件后,您可以做的是检查缓存是否匹配,如果找到任何匹配项,则使用该项响应事件。然后启动提取请求以更新缓存。 现在,如果找不到任何内容,请启动提取请求,克隆响应(因为响应主体只能使用一次),使用原始响应响应响应,然后使用克隆的响应更新缓存。

    我们用它做了什么?

    无论用户是在线、离线还是在线,用户都会得到即时响应!

    服务器最多收到一个请求,缓存将始终使用来自服务器的最新数据进行更新!

    serviceworke.rs 是一个很好的资源,可以帮助您了解如何与服务人员一起做许多有趣的事情。

    This page 更详细地解释一下我上面所说的是如何工作的。

    推荐文章