<< Back to the blog

HTML5 - Web Worker




By @islamzatary

List of Advanced HTML5 Topics:


Web Worker

JavaScript Concurrency.
JavaScript is a single-threaded environment, meaning multiple scripts cannot run at the same time.
to solve this problem, by using techniques like setTimeout(); setInterval(), XMLHttpRequest.
all of these features run asynchronously, Asynchronous events are processed after the current executing script has yielded.

Web Workers: Bring Threading to JavaScript

Uses: more CPU intensive tasks
Web Workers allow you to do things like fire up long-running scripts to handle computationally intensive tasks, but without blocking the UI or other scripts to handle user interactions.
unresponsive script

Web Worker

Web Workers run in an isolated thread, the code that they execute needs to be contained in a separate file, the first thing to do is create a new Worker object in your main page.
var worker = new Worker('task.js');
the browser will spawn a new worker thread, which is downloaded asynchronously.
The worker will not begin until the file has completely downloaded and executed.
If the path to your worker returns an 404, the worker will fail silently.

Web Worker

After creating the worker, start it by calling the postMessage() method
worker.postMessage(); : Communication between a work and its parent page.
postMessage() can accept either a string or JSON object.
stop a worker: worker.terminate() //main page.
self.close() // worker itself.
Example: http://jsbin.com/vacax/1/edit
Example: http://jsbin.com/qokilo/1/edit

The Worker Environment

Features Available to Workers
The navigator object.
The location object (read-only).
XMLHttpRequest.
setTimeout()/clearTimeout() andsetInterval.
The Application Cache.
Importing external scripts using the importScripts() method.

Workers do NOT have access to:

The DOM (it's not thread-safe).
The window object.
The document object.
The parent object.

Inline Workers

Blob(),
you can "inline" your worker in the same HTML file as your main logic by creating a URL handle to the worker code as a string

Check Example

Use Cases

Demos

demo1
demo2
demo3

HTML5 - Web Worker




Wrapping up







<< Back to the blog

by @islamzatary