How To Use Javascript Workers (Very Simple Example)

Welcome to a tutorial and example on how to use Javascript workers. So you have heard of Javascript workers and their “threading powers”. But just how do we create and use Javascript workers?

Using Javascript workers is somewhat similar to performing an AJAX call to a server-side script. We send data to a worker to be processed, and the worker responds back with the results.

  1. Create the Javascript worker script. Set it to do processing on receiving a message, and respond with the results.
    • onmessage = evt => postMessage(+evt.data.a + +evt.data.b);
  2. On the “main page”, simply create a worker object and send data to it.
    • var work = new Worker("WORKER.JS");
    • work.postMessage({ a:8, b:9 });
    • work.onmessage = evt => console.log(evt.data);

Yep, it’s that simple. But read on if you need a detailed example!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/how-to-use-javascript-workers-simple-example/” title=”How To Use Javascript Workers – Simple Example” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JAVASCRIPT WORKER EXAMPLE

All right, let us now get into the simple example of Javascript workers in this section.

 

STEP 1) CREATE WORKER SCRIPT

1-worker.js
// (A) ON RECEIVING DATA FROM "MAIN PAGE"
onmessage = evt => {
  // (A1) DO PROCESSING
  console.log("Worker has received data");
  console.log(evt.data);
  var result = +evt.data.a + +evt.data.b;
 
  // (A2) RESPOND BACK TO "MAIN PAGE"
  postMessage(result);
};
 
// (B) OPTIONAL - HANDLE ERRORS
onmessageerror = err => console.error(err);
onerror = err => console.error(err);

This should be very straightforward, do whatever processing is required in your worker script. There are only 3 “important” events to take care of:

  • onmessage When the worker receives data from the “main page”. Use this as the “cue to start processing”.
  • onmessageerror When the data from the “main page” cannot be deserialized. I.E. Corrupted data.
  • onerror Whatever error happens.

 

 

STEP 2) CREATE WORKER OBJECT IN “MAIN PAGE”

2A) DUMMY HTML FORM

2-main.html
<!-- (A) DUMMY HTML FORM -->
<form onsubmit="return workDemo()">
  <input type="number" id="numA" required value="99">
  <input type="number" id="numB" required value="101">
  <input type="submit" value="Go!">
</form>

For this example, we will do the very unproductive process of sending 2 numbers to the worker script to be added together…

 

2B) WORKER PROCESSING

2-main.html
// (B) CREATE A NEW WORKER
var work = new Worker("1-worker.js");
 
// (C) DO THIS ON WORKER RESPONSE
work.onmessage = evt => {
  console.log("Worker has responded");
  console.log(evt.data);
};
 
// (D) OPTIONAL - MANAGE ERRORS
work.onerror = err => {
  console.error("Worker script error!");
  console.error(err);
};
 
// (E) SEND DATA TO WORKER
function workDemo () {
  work.postMessage({
    a: document.getElementById("numA").value,
    b: document.getElementById("numB").value
  });
  return false;
}

Yep, as in the introduction –

  • We create a work = new Worker("1-worker.js") object.
  • Send data (or message) to the worker – work.postMessage(DATA).
  • Lastly, the worker will respond back with the results when it is done processing – work.onmessage = evt => {...}.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

RESTRICTION – NO ACCESS TO DOM!

Take extra note, workers do not have access to the DOM. That is, document and window do not exist in the worker. Think of it this way – Workers are “standalone Javascript processes”.

 

SAME-ORIGIN POLICY APPLIES

The same-origin policy applies to workers.

  • If your website is http://site.com, the worker script must be loaded from the same domain – new Worker("http://site.com/WORKER.JS")
  • That is, it will not work if you try to load the worker script from another domain or CDN – new Worker("http://another-site.com/WORKER.JS")

 

MULTI-THREADING HICCUPS

Workers may seem to be the miracle pill for system performance, but there is a possible critical flaw when it comes to clashes in computations. Watch this video if you are interested.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Workers Example (Click to Enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *