JavaScript is a language of theWeb. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let us look at the previous articles of the series:
In the last article we learned about ECMAScript 6 and now we will understand some features which developers can use to process complex scripts in background via Web Workers.
Web Worker
A web worker is a JavaScript running in the background, without affecting the performance of the page. They are generally external script files that run in the background. It is supported by majority of browsers:
Advantages
We know web browsers increased a lot over the past few years and it is primarly because of lot of work done on its engines, ex- V8 (Google), Chakra (Microsoft). The JavaScript so far runs in a single thread. The problem with single threaded architecture is that it blocks the code and UI becomes unresponsive incase of running complex script. There are various ways to solve this problem:
- Offload work to server, but to make apps faster fat client is preferred
- Use asynchronous calls, but many complex ecysystem of async calls & promises could lead into callback hell
- Leverage multi threading. Interesting!
Web Workers solve this issue by providing capability of multi threading in JavaScript.
Let's define a problem first and solve for that.
Problem statement
If you run a heavy JavaScript script then the UI becomes unresponsive and throws the following error. This is a very common problem “Unresponsive script” that we all have seen some day or the other.
I've written sample code with a problem and the solution also.
Index.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>Unresponsive dialog problem</title>
- </head>
- <body>
- <input id="num">
- <button id="btnWordsSol">Get Words - Solution</button>
- <button id="btnWordsPrb">Get Words - Problem</button>
- <button id="btnTerminate">Terminate</button>
- <button id="btnClear">Clear</button><br><br>
- <div id="msg"></div>
- <script type="text/javascript" src="js/vendor/jquery-1.10.2.min.js"></script>
- <script type="text/javascript">
- var worker=new Worker('js/solutions.js');
- $('#btnClear').click(function() {
- $('#msg').text('');
- });
-
- $('#btnTerminate').click(function() {
- $('#msg').text('');
- if(worker)
- {
- worker.terminate();
- worker=null;
- $('#msg').text('worker destroyed');
- $('#prg').val(0) ;
- }
- });
- $('#btnWordsSol').click(function() {
- $('#msg').text('');
-
- var num=$('#num').val();
- if(worker == null)
- worker=new Worker('solution.js');
- worker.postMessage(num);
- worker.onmessage=function(event) {
- if(event.data.percent!=null)
- $('#prg').val(event.data.percent)
- $('#msg').text(event.data.showText);
- }
-
- worker.onerror=function(event) {
- $('#msg').text(event.lineno+ ' : '+ event.message);
- }
- });
-
- $('#btnWordsPrb').click(function() {
- $('#msg').text('');
-
- var text1="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore t dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
- var arrOfWords=text1.split (" ");
- // console.log('length of our para: '+arrOfWords.length) ;
- var tempStr="";
- var index;
- var num=$('#num').val();
- for (var i = 1; i <= num; i++) {
- index= Math.floor(Math.random()*arrOfWords.length);
- tempStr+=" "+arrOfWords[index];
- }
- $('#msg').text(tempStr);
-
- });
- </script>
-
- </body>
- </html>
Download this code and run this in the webserver, for example http://localhost/webworker/index.html
It looks like this:
Enter any number, say 100 in the text box and click “Get Words – Problem” and see the output of random words, for example:
This button will work if you want to generate the number of words in the text box, say 1000000 (it may be less at your machine). But if you enter a higher value, say 10000000, then after clicking “Get Words – Problem” it'll throw the following message after some time:
Solution
To solve these problems, let's leverage the WW provided by HTML5. Enter the same number in the text box 10000000 and click “Get Words – Solution” and it'll work. We'll review Web Worker life cycle, i.e.,
- spawning a worker (installing, activate)
- idle
- post message
- terminate
- error
Spawning a worker
To create a Web Worker is simple and you need a new JavaScript file which contains code that you want WebWorker to execute. Hence, below code will create a new object from Worker.
- $('#btnWordsSol').click(function()
-
- var worker=new Worker('solution.js');
Communicating with a Web Worker
To use these Web Workers in real world you need to establish a communication. These messages could be simple string, objects. The preceding line will load the script located at “worker.js” and execute it in the background. You need to call the Worker() constructor with the URI of a script to execute in the Worker thread as in the following:
- worker.postMessage(num);
-
- worker.onmessage=function(event) {
- if(event.data.percent!=null)
- $('#prg').val(event.data.percent)
- $('#msg').text(event.data.showText);
- }
If you want to get data from the Worker (for example, the output of the processed information, notifications, and so on) then you should set the Worker's onmessage property to an appropriate event handler function. The onmessage event is callback that receives the value from the background JavaScript. It also sends data back via postMessage.
Capturing error
Web Workers support onerror event. The onerror event captures a JavaScript error that occurs in the background JavaScript.
- worker.onerror=function(event) {
- $('#msg').text(event.lineno+ ' : '+ event.message);
- }
If you want to terminate WW in between then you can click the Terminate button that will kill between the worker processes as in the following:
worker.terminate();
You can use self or this keyword to access onmessage. It's sending data back to problem.html via self.postMessage.
So, communication between the foreground thread running problem.html and the background thread running solution.js is done via postMessage.
Theory of WW
WW runs JavaScript via background thread. Don't be surprised, JavaScript now has background thread execution capability. We know JavaScript is single-threaded and scripts execute sequentially.
But, it's a real thread, spawned by the OS, that executes in the background.
Features available to WW
Due to the multi-threaded behavior, a WW only has access to the following subset of JavaScript features:
- the navigator object
- the location object
- XMLHttpRequest
- setTimeOut/clearTimeOut/setInterval/clearInterval
- importScripts
- spawning other WW
Limitations of WW
It has some limitations apart from it's multithreading advantage, i.e., it can't access:
- DOM elements
- window object
- document object
- parent object
Types WW
Primarily there are three dedicated, shared and inline workers. What we've seen above is an example of dedicated. I'll post another blog for shared and inline in detail and some more interesting features. Keep watching this space.
Please share feedback.