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!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Javascript Worker Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Use http:// to access 2-main.html, not file://.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

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 = parseInt(evt.data.a) + parseInt(evt.data.b);
 
  // (A2) RESPOND BACK TO "MAIN PAGE"
  postMessage(result);
};
 
// (B) OPTIONAL - HANDLE ERRORS
onmessageerror = (err) => { console.log(err); };
onerror = (err) => { console.log(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 that happens.

 

 

STEP 2) CREATE WORKER OBJECT IN “MAIN PAGE”

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…

 

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.log("Worker script error!");
  console.log(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) => {...}.

 

 

USEFUL 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.