Code has been added to clipboard!

How and When to Use HTML5 Web Workers?

Reading time 2 min
Published Feb 27, 2019
Updated Oct 1, 2019

TL;DR – Web workers are JavaScript codes running in the background without disturbing web page performance.

Web Workers Explained

Using web workers in HTML5 allows you to prevent the execution of bigger tasks from freezing up your web page. A web worker performs the job in the background, independent of other scripts and thus not affecting their performance. The process is also called threading, i.e., separating the tasks into multiple parallel threads. During the time, the user can browse normally, as the page stays fully responsive.

In the example below, you can see a simple script for a web worker made for counting numbers:

Example
var i=0;

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

timedCount();

The script contains a postMessage() method which allows posting a message (i.e., the numbers) to an HTML document. However, web workers are not usually used from such simple tasks as they wouldn't use a lot of CPU power and disturb website performance anyway.

A Full Web Worker Code

The code for web workers in HTML5 has to be stored in an external JavaScript file. However, for them to work properly, you also have to include some code in your HTML document:

Example
<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="res"></output></p>
<button onclick="startCounting()">Start Counting</button> 
<button onclick="stopWorker()">Stop Counting</button>

<p><strong>Note:</strong>All Internet Explorer versions before 9, do not support the Web Workers.</p>

<script>
 var l;
 
function startCounting() {
  console.log("Worker started");
  if(typeof(Worker) !== "undefined") {
    if(typeof(l) == "undefined") {
      l = new Worker("demo_workers.js");
    }
    l.onmessage = function(event) {
      document.getElementById("res").innerHTML = event.data;
    };
  } else {
    document.getElementById("res").innerHTML = "Browser does not support Workers";
  }
}
 
function stopWorker() { 
  console.log("Worker terminated");
  l.terminate();
  l = undefined;
}
</script>

</body>
</html>

We'll explain the most crucial parts of the code in the table below.

Code section Meaning
var l;
function startCounting() {
Sets up a global variable
if(typeof(l) == "undefined") {
l = new Worker("demo_workers.js");
}
Initializes a web worker
l.onmessage = function(event) {
document.getElementById("res").innerHTML = event.data;
};
Allows listening to messages and updating the page accordingly
} else {
document.getElementById("res").innerHTML = "Browser does not support Workers";
}
}
Informs the user if their browser doesn't support web workers
function stopWorker() {
console.log("Worker terminated");
l.terminate();
l = undefined;
}
Terminates the web worker

Web Workers: Useful Tips

  • By using setInterval() and setTimeout() JavaScript functions, you can make web workers perform periodic tasks.
  • You cannot access DOM elements using web workers, so don't include any in their scripts.
  • Not sure when to use web workers? The most common tasks include spell checking, syntax highlighting, prefetching and caching data.

Browser support

Chrome
4+
Edge
All
Firefox
3.5+
IE
10+
Opera
10.6+
Safari
4+

Mobile browser support

Chrome
18+
Firefox
4+
Opera
11+
Safari
5.1+
Basics
Introduction
Syntax
Editors
Basic Examples
Head Section
<!DOCTYPE>
Tags and Elements
Semantic Elements
Tags Reference
Attributes
Comments
Block and Inline Elements
Forms
Form Elements
Input
Responsive Web Design
Inline Scripts
Uniform Resource Locator
Redirect
XHTML
Geolocation
Drag and Drop
Local Storage
Web Workers
Server-Sent Events
Character Encoding
Text Formatting
Quotation and Citation Elements
Headings
Paragraphs
Links
Tables
Lists
Symbols
Space
Tab
Styles
Computer Code
Layout
Classes
Colors
Images
iframes
Audio Player
Video Player
YouTube Videos
Multimedia
Canvas
SVG
<!-- -->
<a>
<abbr>
<acronym> DEPRECATED
<address>
<applet> DEPRECATED
<article>
<aside>
<audio>
<b>
<base>
<basefont> DEPRECATED
<bdi>
<bdo>
<big> DEPRECATED
<blink> DEPRECATED
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center> DEPRECATED
<cite>
<code>
<col>
<colgroup>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir> DEPRECATED
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font> DEPRECATED
<footer>
<form>
<frame> DEPRECATED
<frameset> DEPRECATED
<h1> – <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<keygen> DEPRECATED
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<menu>
<menuitem> DEPRECATED
<meta>
<meter>
<nav>
<noframes> DEPRECATED
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike> DEPRECATED
<strong>
<style>
<sub>
<summary>
<sup>
<table>
<tbody>
<td>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt> DEPRECATED
<u>
<ul>
<var>
<video>
<wbr>