50
edits
Changes
→Web Workers API
</p>
== Basic Syntax ==
<p>
Web Workers are created by a constructor function ''Worker()'':
</p>
<pre>const myWorker = new Worker('worker.js');</pre>
<p>
In order to pass information between workers and the main thread ''postMessage()'' method and the ''onmessage'' event handler are used. The following is an example of how to send a simple string to the web worker:
</p>
<pre>myWorker.postMessage('Text message');</pre>
<p>
Then inside our worker we can use ''onmessage'' to handle the incoming message and send some response back to the main thread:
</p>
<pre>
onmessage = function(e) {
console.log('Message received from main script');
var workerResult = 'Result: ' + e;
console.log('Posting message back to main script');
postMessage(workerResult);
}
</pre>
<p>
Finally, back in the main thread we receive the message with the following:
</p>
<pre>
myWorker.onmessage = function(e) {
result.textContent = e.data;
console.log('Message received from worker');
}
</pre>
== Limitations ==
<p>
Worker thread has its own context and therefore you can only access selected features inside a worker thread. For instance, there a three main limitations:
<ul>
<li>You can't directly manipulate the DOM from inside a worker.</li>
<li>You can not use some default methods and properties of the window object since window object is not available inside a worker thread.</li>
<li>The context inside the worker thread can be accessed via ''DedicatedWorkerGlobalScope'' or ''SharedWorkerGlobalScope'' depending upon the usage.</li>
</ul>
</p>
== Dedicated Worker ==