HTML Web Workers API

A Web Worker is a JavaScript script that runs in the background, without affecting the pages performance.

A Web Worker is a JavaScript script that runs in the background, without affecting the page's performance.

 

What is a Web Worker?

When executing scripts in an HTML page, the page will not respond until the script finishes.

A Web Worker is a JavaScript script that runs in the background, independently of other scripts, without affecting page performance. You can continue doing whatever you want: clicking, selecting items, etc., while the Web Worker runs in the background.

Browser support

The numbers in the table indicate the browser version that first fully supported WebWorker.

API
Web Workers
Google Chrome MS Edge Firefox Safari Opera
4.0 10.0 3.5 4.0 11.5

Examples of HTML Web Workers

The example below creates a simple web worker that counts numbers in the background:

 

Count numbers:

Check Web Worker support

Before creating a web worker, check if the user's browser supports it:

if (typeof(Worker) !== "undefined") { // Yes! Web worker support! // Some code. } else { // Sorry! No Web Worker support. }

Create a Web Worker file

Now, let's create the web worker in an external JavaScript file.

Here, the article creates a valuable script. The script is stored in the file "demo_workers.js" :

var i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()",500); } timedCount();

The crucial part of the code above is the method postMessage()– used to post the message back to the HTML page.

Note : Web workers are typically not used for simple scripts like this, but rather for tasks that require more CPU resources.

Create a Web Worker object

Now that we have the web worker file, the next step is to call it from an HTML page.

 

The following lines will check if the worker already exists - it creates a new web worker object and runs the code in "demo_workers.js" :

if (typeof(w) == "undefined") { w = new Worker("demo_workers.js"); }

Then, we can send and receive messages from the web worker.

Add the "onmessage" event listener to the web worker.

w.onmessage = function(event){ document.getElementById("result").innerHTML = event.data; };

When a web worker posts a message, the code in the event listener is executed. Data from the web worker is stored in event.data.

Terminate a web worker.

When a web worker object is created, it will continue listening for messages (even after the external script terminates) until it finishes.

To terminate the web worker and free use of computer/browser resources, use the following method terminate():

w.terminate();

Reuse Web Worker

If you set the worker variable to undefined, you can reuse the code after it's terminated:

w = undefined;

Complete sample code for Web Worker

The Code Worker has appeared in the .js file. Below is the code for the HTML page:

Count numbers:

   

Web Worker and DOM

Because web workers are located in external files, they do not have access to the following JavaScript objects:

  • Window object
  • Document object
  • Father

See more:

Related posts
  • HTML SSE API

    server-sent events (sse) allow a website to receive updates from a server.
  • HTML Web Storage API

    web hosting is more secure, and large amounts of data can be stored locally without impacting website performance.
  • HTML Drag & Drop API

    in html, any element can be dragged and dropped.
Other HTML articles
  • HTML Web Storage API

    lưu trữ web an toàn hơn và một lượng lớn dữ liệu có thể được lưu trữ cục bộ mà không ảnh hưởng đến hiệu suất trang web.
  • HTML Drag & Drop API

    trong html, bất kỳ phần tử nào cũng có thể được kéo và thả.
  • HTML Geolocation API

    html geolocation api được sử dụng để xác định vị trí của người dùng.
  • YouTube video in HTML

    cách dễ nhất để phát video bằng html là sử dụng youtube.
  • Inserting video in HTML5

    cách chèn video vào html như thế nào? nếu đang muốn tìm hiểu cách chèn video vào website html, mời bạn tham khảo bài viết dưới đây.
  • What is HTML? Basic HTML structure

    html là một phần không thể thiếu khi nói đến lập trình web. mức độ phổ biến của html ngày càng tăng và nó được coi là tiêu chuẩn web chính thức. vậy cụ thể html là gì? html ra đời như thế nào và cấu trúc của html ra sao? hãy cùng tìm hiểu ngay sau đây nhé.
Category

System

Windows XP

Windows Server 2012

Windows 8

Windows 7

Windows 10

Wifi tips

Virus Removal - Spyware

Speed ​​up the computer

Server

Security solution

Mail Server

LAN - WAN

Ghost - Install Win

Fix computer error

Configure Router Switch

Computer wallpaper

Computer security

Mac OS X

Mac OS System software

Mac OS Security

Mac OS Office application

Mac OS Email Management

Mac OS Data - File

Mac hardware

Hardware

USB - Flash Drive

Speaker headset

Printer

PC hardware

Network equipment

Laptop hardware

Computer components

Advice Computer

Game

PC game

Online game

Mobile Game

Pokemon GO

information

Technology story

Technology comments

Quiz technology

New technology

British talent technology

Attack the network

Artificial intelligence

Technology

Smart watches

Raspberry Pi

Linux

Camera

Basic knowledge

Banking services

SEO tips

Science

Strange story

Space Science

Scientific invention

Science Story

Science photo

Science and technology

Medicine

Health Care

Fun science

Environment

Discover science

Discover nature

Archeology

Life

Travel Experience

Tips

Raise up child

Make up

Life skills

Home Care

Entertainment

DIY Handmade

Cuisine

Christmas

Application

Web Email

Website - Blog

Web browser

Support Download - Upload

Software conversion

Social Network

Simulator software

Online payment

Office information

Music Software

Map and Positioning

Installation - Uninstall

Graphic design

Free - Discount

Email reader

Edit video

Edit photo

Compress and Decompress

Chat, Text, Call

Archive - Share

Electric

Water heater

Washing machine

Television

Machine tool

Fridge

Fans

Air conditioning

Program

Unix and Linux

SQL Server

SQL

Python

Programming C

PHP

NodeJS

MongoDB

jQuery

JavaScript

HTTP

HTML

Git

Database

Data structure and algorithm

CSS and CSS3

C ++

C #

AngularJS

Mobile

Wallpapers and Ringtones

Tricks application

Take and process photos

Storage - Sync

Security and Virus Removal

Personalized

Online Social Network

Map

Manage and edit Video

Data

Chat - Call - Text

Browser and Add-on

Basic setup