3. The Problem: JavaScript Concurrency
◦ Compatibility
◦ Static typing
◦ Accessibility
◦ Performance
◦ JavaScript is a single-threaded environment.
◦ multiple scripts cannot run at the same time.
4. The Problem: JavaScript Concurrency
Developers mimic 'concurrency' by using techniques.
◦ setTimeout()
◦ setInterval()
◦ XMLHttpRequest
◦ event handlers.
6. Web Workers
The Web Workers specification defines an API for running scripts in the background
independently of any user interface scripts.
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.
7. Types of Web Workers
There are two kinds of workers,
◦ Dedicated Workers.
◦ Shared Workers.
8. Dedicated Workers
◦ The code must be contained in a separate file.
◦ Communication via message passing.
◦ Event listeners to catch messages between source and worker.
9. Dedicated Workers
Step 1 - Create a new Worker object in your main page.
var worker = new Worker('task.js');
10. Dedicated Workers
Step 2 - Communicating with a Worker via Message Passing.
Main script:
The worker:
worker.postMessage('Hello World');
worker.postMessage({'cmd': 'start', 'msg': 'Hi'});
self.postMessage('Hello Back');
11. Dedicated Workers
Step 3 - Listen to message event.
Main script:
The worker:
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data); }, false);
self.addEventListener('message', function(e) {
self.postMessage(e.data); }, false);
12. Dedicated Workers
Step 4 - Stop a worker.
Main script:
The worker:
worker.terminate();
self.close ();
13. Check Web Worker Support
If (typeof(Worker) !== "undefined") {
// Yes! Web worker support!
} else {
// Sorry! No Web Worker support..
}
15. Handling Errors
◦ When an error occurs while a worker is executing, onerror event handler is called.
◦ Receives an event named error.
◦ Message - A human-readable error
◦ Filename - The name of the script file in which the error occurred.
◦ lineno - The line number of the script file on which the error occurred.
17. Subworkers(Nested Workers)
Workers have the ability to spawn child workers.
limitations
◦ Subworkers must be hosted within the same origin as the parent page.
◦ URIs within subworkers are resolved relative to their parent worker's location rather than that
of the owning page.
18. Communicating objects
Can pass more complex types in/out of Workers.
◦ String, JSON object.
◦ File, Blob, ArrayBuffer(using structured cloning algorithm).
Messages passed between the main page and workers are copied, not shared.
19. Transferrable objects
◦ Data is transferred from one context to another.
◦ Like pass-by-reference but calling context is no longer available once transferred to the new
context.
worker.postMessage(arrayBuffer, [arrayBuffer]);
window.postMessage(arrayBuffer, targetOrigin, [arrayBuffer]);
20. Features Available to Workers
◦ The navigator object
◦ The location object (read-only)
◦ XMLHttpRequest
◦ setTimeout()/clearTimeout() andsetInterval()/clearInterval()
◦ The Application Cache
21. Limitations of Web Workers
LIMITED ACCESS
◦ The DOM (it's not thread-safe)
◦ The window object
◦ The document object
◦ The parent object
22. Limitations of Web Workers
SAME ORIGIN POLICY
◦ All of your worker scripts must be served from the same domain as the script that is
attempting to create the worker.
◦ This also applies to the protocol. For example a https:// page cannot call on a worker served
using http://.
23. Limitations of Web Workers
RESTRICTED LOCAL ACCESS
◦ Web Workers will not work if the web page is being served directly from the filesystem (using
file://)
◦ But can overcome using,
◦ local development server such as XAMPP
◦ Using Inline Workers with blob URLs.
var blob = new Blob([
"onmessage = function(e) { postMessage('msg from worker'); }"]);
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
24. Use Cases of Web Workers
◦ Prefetching and/or caching data for later use
◦ Code syntax highlighting or other real-time text formatting
◦ Spell checker
◦ Analyzing video or audio data
◦ Background I/O or polling of web services
◦ Processing large arrays or humungous JSON responses
◦ Image filtering in <canvas>
◦ Updating many rows of a local web database
imagine a site that needs to handle UI events, query and process large amounts of API data, and manipulate the DOM. Pretty common, right? Unfortunately all of that can't be simultaneous due to limitations in browsers' JavaScript runtime
There are a number of bottlenecks preventing interesting applications from being ported (say, from server-heavy implementations) to client-side JavaScript. Some of these include browser compatibility, static typing, accessibility, and performance. Fortunately, the latter is quickly becoming a thing of the past as browser vendors rapidly improve the speed of their JavaScript engines.
all of these features run asynchronously, but non-blocking doesn't necessarily mean concurrency. Asynchronous events are processed after the current executing script has yielded.
Bring Threading to JavaScript
Web Workers run in an isolated thread. As a result, the code that they execute needs to be contained in a separate file.
Once the Web Worker is spawned, communication between web worker and its parent page is done using message passing.
If the specified file exists, 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.
Messages passed between the main page and workers are copied, not shared. For example, in the next example the 'msg' property of the JSON message is accessible in both locations. It appears that the object is being passed directly to the worker even though it's running in a separate, dedicated space. In actuality, what is happening is that the object is being serialized as it's handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each pass. Most browsers implement this feature by automatically JSON encoding/decoding the value on either end.
When a runtime error occurs in worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface.
This is great for f.
Before you go spawning a worker farm, be cautious about hogging too many of the user's system resources. One reason for this is that messages passed between main pages and workers are copied, not shared. urther breaking up large tasks at runtime
It appears that the object is being passed directly to the worker even though it's running in a separate, dedicated space. In actuality, what is happening is that the object is being serialized as it's handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each pass. Most browsers implement this feature by automatically JSON encoding/decoding the value on either end.
Due to the fact that your Web Workers run outside of the main application thread they do not have the same access to JavaScript features as your main application does.