Web Workers for Beginners and without external files
Some people still might not have heard of an really awesome and cool feature called Web Workers... this is just not acceptable! Why? Because they are simply awesome!
A basic introduction
With web workers you're able to build multi-threaded javascript applications, you heard right! multi-threaded! Imagine the following: You're building a really cool game using WebGL and have tons of stuff to calculate... but you only have single instance of the browser and the script needs to calculate everything at once... overkill! With web workers you have the possibility to let those calculations be done in the background while your script happily goes on. Pure epicness for calculating some artificial intelligence, especially if its kinda heavy, just pass it over to another thread.
One downside... web workers don't have access to the DOM. See them as standalone app to calculate processing heavy things without disturbing your actual app. This makes life easier!
A basic web worker
So how do we create that neat little thing? Hard to achieve? No! Piece of cake. Just check out the following example:
var myWorker = new Worker('/some/path/externalCalculation.js');
myWorker.onmessage = function(event) {
console.log('We got some data delivered!', event.data);
};
As you can see... there is no big programming behind this, its even somewhat similar to programming of sockets or some other connection. A web worker can send back data to the main app and the main app can listen to this. Sounds familiar, doesn't it?
Example without external file using Blob()
With blobs you can now create files directly via javascript. For more information about Blob()
head over to MDN.
HTML
<div id="counter"></div>
<script id="myWorker">
var i = 0;
setInterval(function() {
i++;
postMessage(i); // sent data to main app
}, 500);
</script>
JavaScript
var myWorker = null,
URL = window.URL || (window.webkitURL); // simple polyfill
window.URL = URL;
// we are creating a new javascript file using blob. we just fetch the content of the script tag
// located in our html file and assign it to the Blob(content,type)
// of course you can also assign the desired function to a variable, instead
// of putting this into a script tag.
var workerData = new Blob([document.getElementById('myWorker').textContent], {
type: "text/javascript"
});
function init() {
if (typeof (Worker) === undefined) { // check if browser supports web workers
alert('No webworker supported');
return false;
}
// create the new web worker
// as we dont have an external file, we have to create a url
// for our blob using createObjectURL. which is somewhat similar to
// base64 encoded images. link will look like
// blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
myWorker = new Worker(window.URL.createObjectURL(workerData));
// listen for messages sent by the worker
myWorker.onmessage = function (e) {
// output
document.getElementById('counter').innerHTML = e.data;
};
}
init();
Written by Christian Weber
Related protips
3 Responses
Someone needs to fix dat code highlighting.
@vohof What exactly do you mean? Seems fine for me?
I rewrite this example without script tag, here fiddle http://jsfiddle.net/e643x/1/