ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

HTML 5 Web Workers

Updated on December 30, 2012
Source

HTML 5 Web Workers handle concurrency in web applications. This means that scripts can run in the background without blocking the UI, thus leaving users to continue to interact with the web page while the script works behind the scenes. The former powerhouse of web concurrency was the XmlHttpRequest which could execute a script by passing the URL of the script to the method which would process the task at the server level and then return the resulting value to the client.

Other techniques was to use the setTimeout(), setInterval() methods to initiate timers to let the script execute in peace. The new Web Worker API that is part of the HTML 5 specification eliminates these bottlenecks and is easy to implement if the browser supports it. In this tutorial, I will review the Web Worker API and provide some examples on its use.

Refer yourself to the table below to see which browser and version is currently supporting this new API.

Current Supported by Browser Version

Browser
Version
Shared Web Workers
Dedicated Web Workers
Chrome
23
YES
YES
Safari
5.1
YES
YES
Internet Explorer
9
NO
NO
Opera
12
YES
YES
Opera Mini
7
NO
NO
iOS Safari
6
YES
YES
Android Chrome
2.1
NO
NO
BlackBerry Browser
7
YES
YES

Initial Web Worker Browser Support

Browser
Shared Web Workers
Dedicated Web Workers
Chrome
22
22
Safari
5.1
5.1
Internet Explorer
10
10
Opera
12
12
Opera Mini
 
 
iOS Safari
5
5
Android Chrome
2.1
2.1
BlackBerry Browser
7
7

WebWorker Specs

WebWorkers are part of the Javascript API in HTML5. The Web Worker API runs within the web app’s sandbox and have limited scope , meaning that they cannot access different parts of a host’s computer. WebWorkers are designed to interface with resources running on a corporate server or cloud like a web service or again from the a web api. They - WebWorkers- are background tasks that doesn’t freeze up a web page where an application or some other content is running.

A simple Web Worker

Creating Web Workers is very simple. For example the following code creates a Web Worker for the process.js JavaScript file that resides on the server.

var myWW = new WebWorker(‘process.js’);

To return some data at the end of WebWorker process, you can use the postMessage which posts message back to the calling web page.

myWW.onmessage = function(event){

document.getElementById('showData').textContent = event.data;

}

The process.js file can include any JavaScript code that is needed to process whatever transaction that is needed as the following example shows:

postMessage('hello world');

SharedWorker

Another type of Web Worker is the SharedWorker. A Web Worker is considered “Shared” when many threads are using the same Web Worker. These threads can be on the same page, from a parent and inline page or different pages. ShareWorkers must implement the portMessage using the port attribute of the SharedWorker. To use the SharedWorker object you will need to implement an AddEventListener with a callback function, either inline or not, as the following example demonstrates.

var sw = new SharedWorker(‘transaction.js’);
sw.port.addEventListener(‘process’, function(evt){

postMessage(‘Hello World ’ + evt.data);

},false);

sw.port.postmessage(‘kevin’); //this is how to pass arguments for the data parameter

Worker (Dedicated)

Dedicated workers are the second type of Web Workers that are defined in the HTML5 specification. Dedicated workers are simple workers as in the example above. Dedicated workers run a single thread on a single page. Like SharedWorkers, DedicatedWorkers act on data through a messaging mechanism. You pass data as arguments, if needed, to the web worker which is a Javascript script stored in a file on the server. The worker returns data in a form of a message at the end of the process. This message can a simple confirmation, an error message, or some data that was fetched from a database or some other process.

You can’t call other server running processes directly as a Web Worker. Meaning you can’t call a php script or a python script or a server running Java Servlet or a .Net process. Web Workers are strictly Javascript based. However, the web worker can call an external process running on the server since the XmlHttpRequest is supported.

Attributes, Timers, Events and Methods

Attributes

WorkerNavigator

The WorkerNavigator is the Javascript Navigator attribute which is the user agent of the end user.

WorkerLocation
The WorkerLocation is the full path of the url, including port, host, hostname, search, pathname and hash.

WorkerGlobalScope
This is the self or this object that defines the scope of the calling object.

Timers
setTimeout and clearTimeout, setInterval() and clearInterval()
These are the standard timers that are supported by the HTML DOM.

Events
Web Workers have two standard events: onmessage and onerror

Methods
postMessage
The postMessage as we have seen manages the communication between the calling page(s) and the Web Worker.

importScripts
The importScripts is a mechanism to permit the addition of multiple external scripts to be added to the main web worker. The importScripts method is a comma delimited string as follows:

importScripts(‘test1.js’, ‘test2.js’, ‘test3.js’);

close
The close method terminates the web worker.

Detecting Web Browser Support

Since not all browser versions support web workers, you will need a way to gracefully handle the detection the available support of the web worker by the browser. You can check to see if the worker object is supported. The DOM will return the undefined message if the object is not supported which you can then try a XmlHttpRequest instead.

Here is a possible implementation example:

var worker = new Worker(‘test.js’);
if(typeof(worker)=="undefined")
{

//try calling calling an XmlHttpRequest instead

}
else
{
// manage any post messages to and from the server or worker.
}

Web workers are a great addition to the HTML specification and will provide a lot of heavy lifting that was previously handled by an assortment of different techniques and will provide a smoother user experience for web applications.

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      5 years ago from Canada

      Thanks for the info. Is Chrome supported on Android now? I think when I wrote this, I was playing around with the default browser.

    • profile image

      Frank 

      5 years ago

      I think you'll find that Dedicated Web Workers are supported on Chrome for Android. However, it isn't supported by the stock Android browser.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)