Internet‎ > ‎HTML‎ > ‎HTML 5‎ > ‎

HTML5 Web Workers

This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.

Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image. The examples below show some appropriate uses of workers.

Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.

<!DOCTYPE HTML>
<html>
<head>
<title>Worker example: One-core computation</title>
</head>
<body>
<p>The highest prime number discovered so far is: <output id="result"></output></p>
<script>

var worker = new Worker('worker.js');
worker.onmessage = function (event) {
document.getElementById('result').textContent = event.data;
};

</script>
</body>
</html>


How Web Workers Work

Web Workers exist almost independently of the page that spawned them. The worker has no access to the spawning page's DOM, and cannot communicate with it directly. All communication between the page and the worker is performed asynchronously via callback functions that accept message strings. Let's construct a simple Worker to see how it works:

//code in the spawning page
var worker = new Worker('worker.js');
worker.onmessage = function(event) 
{
    alert("Worker says: " + event.data);
};
worker.postMessage('Dave');


//worker.js
onmessage = function(event) 
{
    var message = "Your name is " + event.data;
    postMessage(message);
};


Source:
Comments