logo Learn HTML
  • Home
  • Tutorials
  • Practice
  • Quiz
  • Projects
  • About
  • Contact

HTML Course

  • HTML HOME
  • HTML Introduction
  • HTML Basic
  • HTML Element
  • HTML Attributes
  • HTML Headings
  • HTML Paragrapha
  • HTML Style
  • HTML Formattin
  • HTML Quotations
  • HTML Colors
  • HTML Css
  • HTML Links
  • HTML Image
  • HTML Favicon
  • Page Tittle
  • HTML Tables
  • HTML Lists
  • Block & Inline
  • HTML Div
  • HTML Classes
  • HTML Id
  • HTML Buttons
  • HTML Iframes
  • HTML File Paths
  • HTML Head
  • HTML Layout
  • HTML Symbols
  • HTML Emojis
  • HTML URL Encode
  • HTML VS XHTML
  • HTML FROM
  • HTML Form
  • Form Attributes
  • Form Elements
  • HTML Input Types
  • HTML Input Attributes
  • Input Form Attributes
  • HTML Graphics
  • HTML Canvas
  • HTML SVG
  • HTML Media
  • HTML Media
  • HTML Video
  • HTML Audio
  • HTML Plug-ins
  • HTML Youtube
  • HTML APIS
  • HTML Web APIS
  • HTML Geolocation
  • HTML Drag & Drop
  • Web Storage
  • Web Workers
  • HTML SSE
  • HTML Examples
  • HTML Examples
  • HTML Editor
  • HTML Quiz
  • HTML Exercises
  • HTML References
  • HTML Tag List
  • HTML Attributes
  • HTML Global Attributes
  • HTML Brower Support
  • HTML Events
  • HTML Colors
  • HTML Canvas
  • HTML Audio & Video
  • HTML Doctypes
  • HTML Character Sets
  • HTML URL Encode
  • Language Codes
  • HTTP Messages
  • HTTP Methods
  • PX to EM Converter
  • keyboard Shortcuts

HTML Web Workers API: Boosting Performance


In a standard web page, JavaScript runs on a single "thread." This means if a script is doing heavy calculations, the page becomes frozen and unresponsive. A Web Worker solves this by running a script in the background, independent of the user interface.


1. What is a Web Worker?

A Web Worker is a JavaScript file that runs in the background. It allows you to perform heavy tasks (like processing large data sets or image manipulation) while the user continues to click, scroll, and interact with the page smoothly


2. Basic Support Check

Always check for browser support before initializing a worker:

Javascript

if (typeof(Worker) !== "undefined") {

// Success! Web Workers are supported.

} else {

// Handle older browsers

console.log("Web Workers are not supported on this browser.");

}


3. Step-by-Step Implementation


Step A: Create the External Worker File

You must put the background code in a separate .js file (e.g., task.js). Inside this file, we use postMessage() to send data back to the main page.

File: task.js

Javascript

let i = 0;

function count() {

i++;

// Send the result back to the main thread

postMessage(i);

setTimeout(count, 500);

}

count();


Step B: Create the Worker Object

On your main HTML page, you initialize the worker and set up an onmessage listener to receive the data.

Main Page Script:

Javascript

let myWorker;


function startTask() {

if (typeof(myWorker) == "undefined") {

myWorker = new Worker("task.js");

}


myWorker.onmessage = function(event) {

}

document.getElementById("result").innerHTML = event.data;

};

}


Step C: Terminate the Worker

Workers consume system resources. When the task is finished, use the terminate() method to stop it and free up the browser's memory.

Javascript

function stopTask() {

myWorker.terminate();

myWorker = undefined; // Clear the variable so it can be restarted

}


4. Important Restrictions

Because Web Workers run in a separate environment, they are isolated from the main page. They cannot access:

  • window object
  • document object (The DOM)
  • parent object

5. Full Working Code Example

You can copy this into your project to see the background counter in action:

HTML

<!DOCTYPE html>

<html>

<body>

<h2> Background Task Demo </h2>

<p> Count: <strong id="result"> 0 </strong> </p>

<button onclick="startWorker()"> Start Task </button>

<button onclick="stopWorker()"> Stop Task </button>


<script>

let w;

function startWorker() {

if (typeof(Worker) !== "undefined") {

if (typeof(w) == "undefined") {

w = new Worker("demo_workers.js");

}

w.onmessage = function(event) {

document.getElementById("result").innerText = event.data;

};

}

}


function stopWorker() {

if (w) {

w.terminate();

w = undefined;

}

}

</script>

</body>

</html>


Summary Table


Feature Main Thread Web Worker
UI Interaction Yes (Handles clicks/scrolls) No
DOM Access Yes No
Heavy Logic No (Will freeze the page) Yes (Ideal for background tasks)
Communication postMessage onmessage

Try It Your Self

Sign Up For New
Update

HTML Basic
  1. HTML Basic
  2. HTML Element
  3. HTML Attributes
  4. HTML Headings
  5. HTML Paragrapha
  6. HTML Tables
  7. HTML Lists
HTML Advance
  1. HTML Div
  2. HTML Classes
  3. HTML Id
  4. HTML Buttons
  5. HTML Iframes
  6. HTML Symbols
  7. HTML Emojis