SlideShare a Scribd company logo
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 (20)

PPTX
Reactjs
Neha Sharma
 
PPT
Javascript
guest03a6e6
 
PDF
JUnit & Mockito, first steps
Renato Primavera
 
PDF
Understanding Sling Models in AEM
Accunity Software
 
PPTX
Ajax and Jquery
People Strategists
 
PPTX
Full stack development
Arnav Gupta
 
PPTX
Soap vs rest
Antonio Severien
 
PDF
JavaScript Fetch API
Xcat Liu
 
PPT
Javascript
Manav Prasad
 
PPT
Js ppt
Rakhi Thota
 
PPT
Asynchronous JavaScript & XML (AJAX)
Adnan Sohail
 
PPTX
Ajax ppt - 32 slides
Smithss25
 
PPTX
Introduction à spring boot
Antoine Rey
 
PPTX
Express js
Manav Prasad
 
PPTX
Asynchronous programming in C#
Bohdan Pashkovskyi
 
PPTX
Java script
reddivarihareesh
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Introduction into ES6 JavaScript.
boyney123
 
PPTX
Introduction to ajax
Pihu Goel
 
PDF
Http methods
maamir farooq
 
Reactjs
Neha Sharma
 
Javascript
guest03a6e6
 
JUnit & Mockito, first steps
Renato Primavera
 
Understanding Sling Models in AEM
Accunity Software
 
Ajax and Jquery
People Strategists
 
Full stack development
Arnav Gupta
 
Soap vs rest
Antonio Severien
 
JavaScript Fetch API
Xcat Liu
 
Javascript
Manav Prasad
 
Js ppt
Rakhi Thota
 
Asynchronous JavaScript & XML (AJAX)
Adnan Sohail
 
Ajax ppt - 32 slides
Smithss25
 
Introduction à spring boot
Antoine Rey
 
Express js
Manav Prasad
 
Asynchronous programming in C#
Bohdan Pashkovskyi
 
Java script
reddivarihareesh
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Introduction into ES6 JavaScript.
boyney123
 
Introduction to ajax
Pihu Goel
 
Http methods
maamir farooq
 

Viewers also liked (12)

PDF
F. Laruina Legionella nei condomini_aspetti pratici
Francesco Laruina
 
PDF
Alessandro Ballocchi - Bari 22 ottobre
infoprogetto
 
PPT
Re Think Group Presentation
damian_85
 
PDF
Intervento dell'arch. Maurizio Varratta
infoprogetto
 
PDF
Growth Hacking @ Sup de Pub International Track — part 1
Maxime Pico
 
PDF
Good for the Bottom Line: Embracing Workplace Culture & Transparency
Glassdoor
 
PDF
Bootstrap, Angel or Venture: Determining the Right Financing Strategy for You...
Judy Loehr
 
PDF
Managing Tomorrow’s Networks: The Impacts of SDN and Network Virtualization o...
CA Technologies
 
PDF
Why lawyers should care about bitcoin
David Smith
 
PDF
50 Outrageous U.S. Laws
Instant Checkmate
 
F. Laruina Legionella nei condomini_aspetti pratici
Francesco Laruina
 
Alessandro Ballocchi - Bari 22 ottobre
infoprogetto
 
Re Think Group Presentation
damian_85
 
Intervento dell'arch. Maurizio Varratta
infoprogetto
 
Growth Hacking @ Sup de Pub International Track — part 1
Maxime Pico
 
Good for the Bottom Line: Embracing Workplace Culture & Transparency
Glassdoor
 
Bootstrap, Angel or Venture: Determining the Right Financing Strategy for You...
Judy Loehr
 
Managing Tomorrow’s Networks: The Impacts of SDN and Network Virtualization o...
CA Technologies
 
Why lawyers should care about bitcoin
David Smith
 
50 Outrageous U.S. Laws
Instant Checkmate
 
Ad

Similar to webworkers (20)

PDF
Web workers
Surbhi Mathur
 
PPTX
Workers
Adrian Caetano
 
PDF
Building Client-Side Attacks with HTML5 Features
Conviso Application Security
 
PDF
Web Storage & Web Workers
Inbal Geffen
 
PPTX
JS basics
Mohd Saeed
 
PPTX
Lecture 5: Client Side Programming 1
Artificial Intelligence Institute at UofSC
 
PPTX
Html web workers
AbhishekMondal42
 
PPT
eXo SEA - JavaScript Introduction Training
Hoat Le
 
PDF
JavaScript
Ivano Malavolta
 
PPT
HTML5 Multithreading
Allan Huang
 
PPTX
7 tips for javascript rich ajax websites
oazabir
 
PDF
Treinamento frontend
Adrian Caetano
 
PPTX
Web worker
Nitin Giri
 
PDF
JavaScript-Core
tutorialsruby
 
PDF
JavaScript-Core
tutorialsruby
 
PDF
Jinx - Malware 2.0
Itzik Kotler
 
PDF
Developing High Performance Web Apps
Timothy Fisher
 
PPTX
Java Script - A New Look
rumsan
 
PDF
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
Fwdays
 
PPTX
Web workers
Ran Wahle
 
Web workers
Surbhi Mathur
 
Building Client-Side Attacks with HTML5 Features
Conviso Application Security
 
Web Storage & Web Workers
Inbal Geffen
 
JS basics
Mohd Saeed
 
Lecture 5: Client Side Programming 1
Artificial Intelligence Institute at UofSC
 
Html web workers
AbhishekMondal42
 
eXo SEA - JavaScript Introduction Training
Hoat Le
 
JavaScript
Ivano Malavolta
 
HTML5 Multithreading
Allan Huang
 
7 tips for javascript rich ajax websites
oazabir
 
Treinamento frontend
Adrian Caetano
 
Web worker
Nitin Giri
 
JavaScript-Core
tutorialsruby
 
JavaScript-Core
tutorialsruby
 
Jinx - Malware 2.0
Itzik Kotler
 
Developing High Performance Web Apps
Timothy Fisher
 
Java Script - A New Look
rumsan
 
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
Fwdays
 
Web workers
Ran Wahle
 
Ad

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

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