SlideShare a Scribd company logo
1 of 27
HTML5 Web Workers
The Problem: JavaScript Concurrency
The Problem: JavaScript Concurrency
◦ Compatibility
◦ Static typing
◦ Accessibility
◦ Performance
◦ JavaScript is a single-threaded environment.
◦ multiple scripts cannot run at the same time.
The Problem: JavaScript Concurrency
Developers mimic 'concurrency' by using techniques.
◦ setTimeout()
◦ setInterval()
◦ XMLHttpRequest
◦ event handlers.
Introducing HTML5 Web Workers
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.
Types of Web Workers
There are two kinds of workers,
◦ Dedicated Workers.
◦ Shared Workers.
Dedicated Workers
◦ The code must be contained in a separate file.
◦ Communication via message passing.
◦ Event listeners to catch messages between source and worker.
Dedicated Workers
Step 1 - Create a new Worker object in your main page.
var worker = new Worker('task.js');
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');
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);
Dedicated Workers
Step 4 - Stop a worker.
Main script:
The worker:
worker.terminate();
self.close ();
Check Web Worker Support
If (typeof(Worker) !== "undefined") {
// Yes! Web worker support!
} else {
// Sorry! No Web Worker support..
}
Loading External Scripts
importScripts('script1.js', 'script2.js');
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.
Dedicated Workers
DEMO
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.
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.
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]);
Features Available to Workers
◦ The navigator object
◦ The location object (read-only)
◦ XMLHttpRequest
◦ setTimeout()/clearTimeout() andsetInterval()/clearInterval()
◦ The Application Cache
Limitations of Web Workers
LIMITED ACCESS
◦ The DOM (it's not thread-safe)
◦ The window object
◦ The document object
◦ The parent object
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://.
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);
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
Browser Support
Questions?
Thank You.

More Related Content

What's hot

What's hot (20)

Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Akka-intro-training-public.pdf
Akka-intro-training-public.pdfAkka-intro-training-public.pdf
Akka-intro-training-public.pdf
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 

Viewers also liked

Intervento dell'arch. Maurizio Varratta
Intervento dell'arch. Maurizio VarrattaIntervento dell'arch. Maurizio Varratta
Intervento dell'arch. Maurizio Varratta
infoprogetto
 

Viewers also liked (12)

F. Laruina Legionella nei condomini_aspetti pratici
F. Laruina Legionella nei condomini_aspetti praticiF. Laruina Legionella nei condomini_aspetti pratici
F. Laruina Legionella nei condomini_aspetti pratici
 
Alessandro Ballocchi - Bari 22 ottobre
Alessandro Ballocchi - Bari 22 ottobreAlessandro Ballocchi - Bari 22 ottobre
Alessandro Ballocchi - Bari 22 ottobre
 
Re Think Group Presentation
Re Think Group PresentationRe Think Group Presentation
Re Think Group Presentation
 
Comp gov -_1_states of seps
Comp gov -_1_states of sepsComp gov -_1_states of seps
Comp gov -_1_states of seps
 
Intervento dell'arch. Maurizio Varratta
Intervento dell'arch. Maurizio VarrattaIntervento dell'arch. Maurizio Varratta
Intervento dell'arch. Maurizio Varratta
 
Growth Hacking @ Sup de Pub International Track — part 1
Growth Hacking @ Sup de Pub International Track — part 1Growth Hacking @ Sup de Pub International Track — part 1
Growth Hacking @ Sup de Pub International Track — part 1
 
Perma model
Perma modelPerma model
Perma model
 
Good for the Bottom Line: Embracing Workplace Culture & Transparency
Good for the Bottom Line: Embracing Workplace Culture & TransparencyGood for the Bottom Line: Embracing Workplace Culture & Transparency
Good for the Bottom Line: Embracing Workplace Culture & Transparency
 
Bootstrap, Angel or Venture: Determining the Right Financing Strategy for You...
Bootstrap, Angel or Venture: Determining the Right Financing Strategy for You...Bootstrap, Angel or Venture: Determining the Right Financing Strategy for You...
Bootstrap, Angel or Venture: Determining the Right Financing Strategy for You...
 
Managing Tomorrow’s Networks: The Impacts of SDN and Network Virtualization o...
Managing Tomorrow’s Networks: The Impacts of SDN and Network Virtualization o...Managing Tomorrow’s Networks: The Impacts of SDN and Network Virtualization o...
Managing Tomorrow’s Networks: The Impacts of SDN and Network Virtualization o...
 
Why lawyers should care about bitcoin
Why lawyers should care about bitcoinWhy lawyers should care about bitcoin
Why lawyers should care about bitcoin
 
50 Outrageous U.S. Laws
50 Outrageous U.S. Laws 50 Outrageous U.S. Laws
50 Outrageous U.S. Laws
 

Similar to webworkers

HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
Allan Huang
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites
oazabir
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
rumsan
 

Similar to webworkers (20)

Web workers
Web workersWeb workers
Web workers
 
Workers
WorkersWorkers
Workers
 
Building Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 FeaturesBuilding Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 Features
 
Web Storage & Web Workers
Web Storage & Web WorkersWeb Storage & Web Workers
Web Storage & Web Workers
 
JS basics
JS basicsJS basics
JS basics
 
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
 
Html web workers
Html web workersHtml web workers
Html web workers
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
JavaScript
JavaScriptJavaScript
JavaScript
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites
 
Treinamento frontend
Treinamento frontendTreinamento frontend
Treinamento frontend
 
Web worker
Web workerWeb worker
Web worker
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
Jinx - Malware 2.0
Jinx - Malware 2.0Jinx - Malware 2.0
Jinx - Malware 2.0
 
Developing High Performance Web Apps
Developing High Performance Web AppsDeveloping High Performance Web Apps
Developing High Performance Web Apps
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
 
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
 
Web workers
Web workers Web workers
Web workers
 

webworkers

  • 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

Editor's Notes

  1. 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
  2. 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.
  3.  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. 
  4. Bring Threading to JavaScript
  5. 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.
  6. 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.
  7. 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.
  8. When a runtime error occurs in worker, its onerror event handler is called.  It receives an event named error which implements the ErrorEvent interface.
  9. 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
  10.  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.
  11. 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.