Using service workers across multiple subdomains

2019-03-26 06:57发布

If my web app consists of more than one subdomain, does that mean I have to have multiple service workers, one for each subdomain? Or can I have one service worker that works across subdomains?

3条回答
祖国的老花朵
2楼-- · 2019-03-26 07:21

Each subdomain is considered a different origin and you must register a service worker for each origin but you can reuse the same source for the service worker by setting the Service-Worker-Allowed response header to the list of scopes the same source can control.

查看更多
欢心
3楼-- · 2019-03-26 07:31

If you mean by multiple domains is that the user can access your site directly on multiple domains like www.example.com and hello.example.com then I believe the answer is yes, you need multiple service workers to handle each.

However, if your main app is served on one domain www.example.com but might call other domains like api.example.com or images.examples.com or even fonts.gstatic.com to load Google Fonts or example.s3.amazonaws.com to load static assets then a single service worker is enough. This is how you can catch and cache (or do whatever you'd like to the requests):

(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/
  });
})();

In the example I am using sw-toolbox library from Chrome team to help you cache different assets.

查看更多
放荡不羁爱自由
4楼-- · 2019-03-26 07:33

Each subdomain is considered a different origin, so yes, you will need to register a service worker for each one. Each of these workers will have its own cache and scope.

查看更多
登录 后发表回答