HTML5: Using WebWorkers



WebWorkers was created to allow execution of javaScript code asynchronously: can be compared to a thread that the webpage can launch and with which it can communicate through specific methods.

webworkers

A small disadvantage … the WebWorkers not have access to the DOM: it must be seen as stand-alone applications, useful to perform challenging tasks without interrupt the current application.

A simple WebWorker

Let’s see how to start a simple thread:

Nothing complicated: the code in the file stepsToBeMade.js are executed and the return data are written in a log. The data are sent back to the parent process (stepsToBeMade.js) by using the postMessage function:

All on one page?

We can choose not to use an external file to define the code of our webworker, packing up everything on a single page using a Blob.

Then we declare a script element containing the code to be executed (a simple counter):

and then we create and start the WebWorker from a blob filled with the contents of the script tag:

Putting it all together

Let’s see the complete example:

Italian version here


Published: June 24 2015