大网数据广告活动
Web 标准与前端开发

InstallEvent: addRoutes() method

· 52CE 我爱测

The **`addRoutes()`** method of the InstallEvent interface specifies one or more static routes, which define rules for fetching specified resources that will be used even before service worker startup. This allows you to, for example, bypass a service worker in cases where you al

Service Workers API

The addRoutes() method of the InstallEvent interface specifies one or more static routes, which define rules for fetching specified resources that will be used even before service worker startup. This allows you to, for example, bypass a service worker in cases where you always want to fetch a resource from the network or a browser Cache, and avoids the performance overhead of unnecessary service worker cycles.

Syntax

addRoutes(routerRules)

Parameters

  • routerRules
    • : A single object, or an array of one or more objects, representing rules for how certain resources should be fetched. Each routerRules object contains the following properties:
      • condition

        • : An object defining one or more conditions that specify which resources should match this rule. The following properties can be included; if multiple properties are used, a resource must meet all specified conditions to match the rule.
          • not
            • : A condition object defining conditions that must explicitly not be met to match the rule. Conditions defined inside a not condition are mutually exclusive with other conditions.
          • or
            • : An array of condition objects. One set of these defined conditions must be met to match the rule. Conditions defined inside an or condition are mutually exclusive with other conditions.
          • requestMethod
            • : A string representing the HTTP method a request should be sent by for it to match the rule, such as "get", "put", or "head".
          • requestMode
            • : A string representing the mode a request should have for it to match the rule, for example "same-origin", "no-cors", or "cors".
          • requestDestination
            • : A string representing the destination of a request, i.e., what content type should be requested, for it to match the rule. Examples include "audio", "document", "script", and "worker".
          • runningStatus
            • : An enumerated value representing the required running status of the service worker for a request to match the rule. Values can be "running" or "not-running".
          • urlPattern
            • : A URLPattern instance, or a URLPattern() constructor input pattern representing the URLs that match the rule. Regular expression capturing groups are not allowed, so URLPattern.hasRegExpGroups must be false.
      • source

        • : An enumerated value or an object specifying the source from which matching resources will be loaded. Possible enumerated values are:

          • "cache"
            • : Resources will be loaded from a browser Cache.
          • "fetch-event"
            • : Resources will be loaded via the service worker's ServiceWorkerGlobalScope.fetch_event event handler. This can be combined with the "runningStatus" condition to load resources from a service worker if it is running and fall back to a static route on the network if it is not.
          • "network"
            • : Resources will be loaded from the network.
          • "race-network-and-fetch-handler"
            • : Attempts are made to load resources from the network and the service worker's ServiceWorkerGlobalScope.fetch_event event handler simultaneously. Whichever one completes first is used.

          The source value can also be set to an object containing a single property, cacheName, the value of which is a string representing the name of a browser Cache. Matching resources will be loaded from this specific named cache if it exists.

Return value

A Promise that fulfills with undefined.

Exceptions

  • TypeError
    • : Thrown if one or more of the rules objects inside routerRules is invalid, or has a source value of "fetch-event" when the associated service worker does not have a ServiceWorkerGlobalScope.fetch_event event handler. Also thrown if you try to combine or with another condition type.

Examples

Route specific requests to the network if the service worker is not running

In the following example, URLs that start with /articles are routed to the network if the service worker is not currently running:

addEventListener("install", (event) => {
  event.addRoutes({
    condition: {
      urlPattern: "/articles/*",
      runningStatus: "not-running",
    },
    source: "network",
  });
});

Route form post requests to the network

In the following example, POST requests to a form are sent directly to the network and bypass the service worker:

addEventListener("install", (event) => {
  event.addRoutes({
    condition: {
      urlPattern: "/form/*",
      requestMethod: "post",
    },
    source: "network",
  });
});

Route certain image type requests to a named cache

In the following example, the browser Cache named "pictures" is used for fetching files with extensions of .png or .jpg:

addEventListener("install", (event) => {
  event.addRoutes({
    condition: {
      or: [{ urlPattern: "*.png" }, { urlPattern: "*.jpg" }],
    },
    source: {
      cacheName: "pictures",
    },
  });
});

[!NOTE] If the cache does not exist, the browser defaults to using the network so that the requested resources can still be obtained provided the network is available.

You can't combine or with another condition — this results in a TypeError. If for example you wanted to match files with extensions of .png or .jpg but only when the requestMethod is get, you'd need to specify two separate conditions:

addEventListener("install", (event) => {
  event.addRoutes(
    {
      condition: {
        urlPattern: "*.png",
        requestMethod: "get",
      },
      source: {
        cacheName: "pictures",
      },
    },
    {
      condition: {
        urlPattern: "*.jpg",
        requestMethod: "get",
      },
      source: {
        cacheName: "pictures",
      },
    },
  );
});

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。