Web Workers API - Web APIs | MDN
Web Workers makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.
概览
收录于
2026年3月17日
学科与领域
computer-science-advanced · parallel-concurrent-computing
年级范围
九年级(高一)–十二年级(高四)
页面类型
Article
简介
Web Workers API Overview
- Core Functionality: Enables running script operations in a background thread, preventing laborious processing from blocking the main UI thread.
- Execution: Workers are created via a constructor (e.g.,
Worker()) and execute a specified JavaScript file. - Communication: Data is exchanged between the main thread and workers using
postMessage()and theonmessageevent handler. Data is copied, not shared. - Limitations: Workers cannot directly manipulate the DOM and lack access to certain default methods/properties of the
Windowobject. - Capabilities:
- Can spawn new workers (same-origin policy applies).
- Can perform network requests using
fetch()orXMLHttpRequest. - Access to standard JavaScript functions (String, Array, JSON, etc.).
- Types of Workers:
- Dedicated Workers: Utilized by a single script; represented by
DedicatedWorkerGlobalScope. - Shared Workers: Accessible by multiple scripts across different windows/iframes within the same domain; requires communication via an active port.
- Service Workers: Act as proxy servers to enable offline experiences, intercept network requests, and manage push notifications/background sync.
- Dedicated Workers: Utilized by a single script; represented by
- Key Interfaces:
Worker: Represents the running thread.WorkerGlobalScope: The base interface for worker contexts (similar toWindowfor main content).WorkerLocation: Defines the absolute location of the executed script.
- Global Scope: While
Windowis unavailable, workers useWorkerGlobalScope-derived contexts (DedicatedWorkerGlobalScope,SharedWorkerGlobalScope,ServiceWorkerGlobalScope) which share many methods via theWindowOrWorkerGlobalScopemixin.
用户评价
暂无已发布的评价,欢迎率先分享您的使用体验。