HTML5 - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

HTML5 Web Workers

HTML5 Web Workers

shape Introduction

HTML5 Web workers are used to handle the JavaScript multiple tasks at a time by running multiple threads. Following are the concepts covered.
  • What are Web Workers
  • Browser Support
  • Web Workers Work

What are Web Workers

shape Description

At the point when executing scripts in a HTML page, the page gets slow until the script is done. A Web Worker is a JavaScript which keeps on running in background, autonomously it runs different scripts, without influencing the execution of the page. User can keep on doing whatever need: clicking, selecting things, etc., while the web specialist keeps running out of sight. While executing the script in a web worker window does not have the direct access to the webpage and DOM API. In order to make the system less responsive Web Workers use the System CPU cycles.

Browser Support

shape Description

HTML5 Web Workers API supported by all the latest browsers.Following are the browser versions supported by HTML5 The code below demonstrates to check if users Browser supports or not. [html]<html> <body> <p id="check"> </p> <button onclick="checkSupport()">Check Browser Support</button> <script> function checkSupport() { if(typeof(Worker)!=="undefined")// test condition { document.getElementById("check").innerHTML = "Awesome! Your browser is perfect for Web Workers API"; // if supported } else { document.getElementById("check").innerHTML = "WTH! Please update your Browser, its as old as a Dinasaur"; // not supported } } </script> </body> </html> [/html] Result By running the above code in a preferred browser following output appears.

Web Workers Work

shape Description

The Web Workers are introduced with the URL of the JavaScript which contains the web worker executable code. The code is used to set the event listener and communicate with the script which is drawn from the main page as follows. Syntax [html]var worker = new Worker("bigLoop.js”);[/html] Then it checks if JavaScript file is present, the browser will send a new thread. if application have multiple script files then user need to use importScripts() method to import those files which takes names of those files as arguments as follows. [html]importScripts(“bigLoop.js”, "demo_workers.js");[/html] Now A postmessage( ) is used to start a web worker and which also used to establish the communication between the web worker and main page. User can access the message passed by web worker by using the onmessage method. The code below demonstrates the onmessage method as follows. [html]<!DOCTYPE HTML> <html> <head> <title>Big for loop</title> <script> var worker = new Worker('bigLoop.js'); worker.onmessage = function (event) { alert("Completed " + event.data + "iterations" ); }; function sayHello(){ alert("Hello sir...." ); } </script> </head> <body> <input type="button" onclick="sayHello();" value="Say Hello"/> </body> </html> [/html] Result By running the above code in a preferred browser following output appears. Now click on Say Hello button then a dialogue box appears a shown below. Now click on OK button then user will get dialogue box with alert message as shown below. The code below is used to demonstrate the JavaScript external file assigned by the web workers named as "demo_workers.js" as shown below. [html]var i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()",500); } timedCount(); [/html] Web workers are stopped by themselves in order to stop the web worker by using terminate() method as shown below. [html] worker.terminate() [/html]

Handling Errors

shape Description

While working with the Web Workers API frequently user can get the some errors, to solve those errors HTML5 introduced error codes as shown below. [html]<!DOCTYPE HTML> <html> <head> <title>Big for loop</title> <script> var worker = new Worker('bigLoop.js'); worker.onmessage = function (event) { alert("Completed " + event.data + "iterations" ); }; worker.onerror = function (event) { console.log(event.message, event); }; function sayHello(){ alert("Hello sir...." ); } </script> </head> <body> <input type="button" onclick="sayHello();" value="Say Hello"/> </body> </html> [/html] Result By running the above code in a preferred browser, following output is obtained.

shape Examples

The code below the over all working of web worker by using all the methods as follows. [html]<!DOCTYPE html> <html> <body> <style> body{font:1em Arial;} button{background:#0000FF; font:Arial; font-style:italic; color:#fff;} output{background:#0000FF; font-size:1.5em; color:#fff;} </style> <p>Count numbers: <output id="result"></output></p> <button onclick="startWorker()">Start Worker</button> <button onclick="stopWorker()">Stop Worker</button> <p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p> <script> var w; function startWorker() { if(typeof(Worker) !== "undefined") { if(typeof(w) == "undefined") { w = new Worker("demo_workers.js"); } w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers..."; } } function stopWorker() { w.terminate(); w = undefined; } </script> </body> </html> [/html] Result By running the above code in a preferred browser following output is obtained.

Summary

shape Points

  • JavaScript is a single threaded language.
  • Web Worker will start by calling the postmessage.
  • Web worker will work based on the JavaScript URL.