在多个子域中使用服务工作者

Joe*_*ini 9 service-worker progressive-web-apps

如果我的网络应用程序包含多个子域,这是否意味着我必须拥有多个服务工作者,每个子域一个?或者我可以让一个跨子域工作的服务工作者吗?

Joe*_*ini 13

每个子域都被认为是不同的来源,所以是的,您需要为每个子域注册一个服务工作者.这些工作人员中的每一个都有自己的缓存和范围.


Sal*_*lva 5

每个子域都被视为不同的源,您必须为每个源注册一个 Service Worker,但是您可以通过将Service-Worker-Allowed响应标头设置为同一源可以控制的范围列表来为 Service Worker 重用相同的源。


mkh*_*tib 5

如果您的意思是多个域是用户可以直接在多个域上访问您的站点www.example.comhello.example.com那么我相信答案是肯定的,您需要多个服务人员来处理每个。

但是,如果你的主要应用是服务于一个领域www.example.com,但可能调用像其他领域api.example.com或者images.examples.com甚至fonts.gstatic.com负荷谷歌字体或example.s3.amazonaws.com 加载静态资产话单服务工作者就足够了。这是您可以捕获和缓存的方式(或对请求执行任何您想要的操作):

(function() {
  var DEFAULT_PROFILE_IMAGE_URL = 'images/default-avatar@200x150.png';

  function profileImageRequest(request) {
    // Load from cacheOnly to avoid redownloading the images since if the user
    // updates their avatar its URL will change.
    return toolbox.cacheOnly(request).catch(function() {
      return toolbox.networkFirst(request).catch(function() {
        return toolbox.cacheOnly(new Request(DEFAULT_PROFILE_IMAGE_URL));
      });
    });
  }

  toolbox.precache([DEFAULT_PROFILE_IMAGE_URL]);
  toolbox.router.get('/(.+)/users/avatars/(.*)', profileImageRequest, {
    origin: /example\.s3\.amazonaws\.com/
  });
})();
Run Code Online (Sandbox Code Playgroud)

在示例中,我使用Chrome 团队的sw-toolbox库来帮助您缓存不同的资产。