Skip to content

Service 工作者

一句话解释

service 工作者是 JavaScript file 那个运行 in background, 启用 offline support, 推送 notifications, and 缓存 for web apps.

用大白话说

A service worker is a special JavaScript script that the browser runs in the background, separate from your web page. It cannot access the DOM directly but can intercept network requests, cache responses, and handle events like push notifications — even when the page is closed.

Service workers are the core technology behind Progressive Web Apps (PWAs). They enable offline functionality by caching resources, background sync, and push notifications. They run on a separate thread and have a specific lifecycle: install → activate → fetch.

To use a service worker, you register it from your page with navigator.serviceWorker.注册('/sw.js'). The service worker file then listens for install, activate, and fetch events to manage caching and offline behavior.

示例

javascript
// In sw.js (service worker)
self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => {
      return cached || fetch(event.request);
    })
  );
});

service 工作者那个 serves cached 响应当 available, falling 后面到 network for uncached 请求.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表