Web Workers Example

by morphcast

HTML

<h1>Web Workers Example</h1>
 
<h3>Calculate the volume of a cylinder</h3>

<label>Enter the radius (cm): </label>
<input type="text" id="radius" /><br />
<label>Enter the height (cm): </label>
<input type="text" id="height" /><br />
<button type="button" onclick="sendWorkerMessage();">Start the worker!</button>

<h3>Results of the Calculation</h3>
<div id="response"></div>

<script type='text/worker' id='worker-script'>
		//Web Worker Script    - calculate the volume of a cylinder
    self.addEventListener('message', function(e) {
        //store the received object in a variable and extract the radius and height values;
        var measurements = e.data;
        var radius = measurements.radius;
        var height = measurements.height;

        //Get the value of Pi
        var pi = Math.PI;

        //Declare the volume variable;
        var volume;

        //perform the calculation and round the result to the nearest 2 decimal places
        volume = (pi * (radius * radius)) * height;
        volume = Math.round(volume, 2);

        //post the calculated volume back to the main script
        postMessage(volume);
    },false);
</script>

CSS

body {
    font-family: sans-serif;
    padding: 10px;
}
h1 {
    font-weight: bold;
    margin-bottom: 10px;
}
h3 {
    margin-top: 10px;
    margin-bottom: 10px;
}
input {
    margin-bottom: 10px;
}

JavaScript

//Worker Helper Script By Brian Grinstead
var WorkerHelper = (function() {

    var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
    var URL = window.URL || window.webkitURL;

    function getURL(script) {
        if (window.Worker && BlobBuilder && URL) {
            var bb = new BlobBuilder();
            bb.append(script);
            return URL.createObjectURL(bb.getBlob());
        }

        return null;
    }

    function getWorker(script, onmessage) {
        var url = getURL(script);
        if (url) {
            var worker = new Worker(url);
            worker.onmessage = onmessage;
            return worker;
        }

        return null;
    }

    return {
        getURL: getURL,
        getWorker: getWorker
    };

})();


// Load a worker from a script of type=text/worker, using the getWorker helper
var scriptTagWorker = WorkerHelper.getWorker(
document.getElementById('worker-script').textContent,
//function to be run when a message is received from the worker


function(e) {
    document.getElementById('response').innerHTML = "<br />The worker has determined that the volume of the cylinder is: " + e.data + "cm<sup>3</sup>";
});

function sendWorkerMessage() {
    //get the radius and height of the cylinder provided by the user in the input fields
    var enteredRadius = document.getElementById("radius").value;
    var enteredHeight = document.getElementById("height").value;

    //Check the radius and height provided by the user, using a regular expression to ensure that they are valid integer numbers
    var numberregex = /^[0-9]+$/;

    if (enteredRadius.match(numberregex) && enteredHeight.match(numberregex)) {

        //Place the user entered values into a JSON object
        var json = {
            "radius": enteredRadius,
            "height": enteredHeight
        };

        //Send the user entered radius and height to the worker in the form of the json object
       ...