Html5 Tutorial : Web Workers
- As a developer or as a user, you might have already encountered an error saying that a JavaScript script is taking too much time to run (also called unresponsive script…), why is that?
JavaScript runs in single-threaded environment.
While a long operation is taking place, the application becomes unresponsive to user interaction.
![[Note]](../images/note.png)
Note Many browsers might think that something is going wrong if a task is taking too much time and they will propose you to kill the script.
-
To circumvent that, most developers used to break a big operation into smaller ones when possible and use
setTimeoutorsetIntervalfor instance.
- The arrival of web workers will now allow developers to run an other script independent from the user interface script in a web application.
Like many features labelled HTML5, web worker is not part of the HTML5 specification but since it contributes to build better application, we are going to describe it.
- Web Workers has its own specification: http://www.w3.org/TR/workers/
What is a web worker?
- A worker is a thread, it allows you to perform tasks in a background process in parallel of the main browser process.
- A worker is a JavaScript file that contains the "tasks" you want to perform in a separate thread.
Be careful though, we cannot access everything we want in a worker. Below is what we can access:
-
navigatorobject. -
locationobject (read-only). -
importScripts()method allows you access to script files in the same domain. -
JavaScript objects such as
Object,Array,Date,Math,String. -
XMLHttpRequestobject. setTimeout()andsetInterval()methods.![[Note]](../images/note.png)
Note We do not have access to the DOM inside a Worker and we do not have access to the page that spawned this same Worker.
-
According to the specification:
Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. … Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost.
-- Web Workers specification http://www.w3.org/TR/workers/#scope Knowing that, when would it be a good fit to use web workers? Generally they are used for scripts that are taking a long time. That could be for instance:
- The classic example you can find on internet ⇒ calculate prime numbers.
- To do operations on a client-side database.
- Parse a large JSON string.
- Image or video processing.
- Etc…
To spawn a new worker:
var robot=new Worker('robot.js');To send a message between the main thread and the worker and vice versa we will use the
postMessagemethod. For instance, to send a message to the worker:robot.postMessage(msg_for_worker);
To receive the message, we need to subscribe to the
messageevent. For instance, for the worker to receive messages from the main thread:self.onmessage=function(event){ //Do something };![[Note]](../images/note.png)
Note The actual message itself is contained in
event.data
Inside a worker, you can register to the error event like this:
self.onerror=function(error){ //Do something };The
ErrorEventinterface which is passed as a parameter to the theerrorevent handler contains the following informations:-
filename: Name of the worker that caused the error -
lineno: Line number where the error occurred -
message: The error message
-
- Web workers are currently supported on Firefox 3.5+, Safari 4.0+, Chrome 6.0+ and Opera 10.6+
- What can cause an unresponsive script in a browser?
You can access the DOM of the page that spawned the worker in the worker?
- True
- False
- Cite 2 use case of using web workers
What is the method used to communicate between the main UI thread and the worker?
-
sendMessage(msg) -
sendMsg(msg) -
postMessage(msg) -
postMsg(msg)
-