Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Web workers

NotificationsYou must be signed in to change notification settings

viatcheslav-zadorozhniy/web-workers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Table of contents

What is their purpose?

Web Workers allows running code (JS file) in a background thread separate from the main execution thread of an app.

Time-intensive processing can be delegated to them not to block/slow down the main thread.

Concepts and usage

A worker is an object created using a constructor (e.g.Worker()) that runs JS file in the background thread.

Most of the standard JavaScript sets of functions are available from inside the worker.But there are some exceptions: for example, you can't access DOM (more details).

Communication between the worker and the main thread is done via a system of messages.Both sides have apostMessage() method to send their messages.

Theonmessage event handler is used to respond to the message (contained within themessage eventdata property).The data is copied (using astructured clone algorithm) rather than shared.

Worker types

  • Dedicated workers - utilized by a single script.
  • Shared workers - utilized by multiple scripts running in different windows, IFrames, etc., within the same domain.
  • Service workers - act as proxy servers between the app, the browser, and the network.

Dedicated worker

Adedicated worker is created using theWorker() constructor, specifying the URL of a script to execute.

E.g.

constworker=newWorker('worker.js');

To startthe demo run:

npm run start:worker

Shared worker

Ashared worker is created using theSharedWorker() constructor, specifying the URL of a script to execute.

E.g.

constsharedWorker=newSharedWorker('shared-worker.js');

To startthe demo run:

npm run shared-worker

Service worker

Aservice worker is an event-driven worker. It can control the routes it is associated with by intercepting and modifying navigation and resource requests.

It is registered using theServiceWorkerContainer.register() method.

E.g.

if('serviceWorker'innavigator){navigator.serviceWorker.register('/service-worker.js');}

To startthe demo run:

npm run service-worker

and then openhttp://localhost:8888/


[8]ページ先頭

©2009-2025 Movatter.jp