HTML5 Multithreading
allanhuang@eSobi.com
Agenda
 Single


Threaded Model

Unresponsive Script

 Multithreading




Web Workers (Dedicated)
Sub Web Workers
Shared Web Workers
Single Threaded Model
Single Threaded Model




JavaScript in a browser executes on a Single
Thread Asynchronous Events
Timer Delay is Not Guaranteed!
Unresponsive Script
 Browser

complains a long-running script and
ask user if it should be stopped
Unresponsive Script
 Solutions


setTimeout()




Use 1ms timeout chunks cause task to complete
slowly overall, but browser UI will remain responsive

Web Workers


Web workers provide background thread support in
the browser
Multithreading
Web Workers







Dedicated Web Workers
Allow long-running script that are not interrupted by
scripts that respond to clicks or other user
interactions
Allows long tasks to be executed without yielding to
keep the page responsive
Checking for Browser Support


Compatibility Tables



if (typeof(window.Worker) !== ‘undefined’) {
// this browser supports web workers
}
Workers Environment


Accessible







The this / self object (worker)
The navigator object
The read-only location object
XMLHttpRequest
setTimeout() / clearTimeout()
setInterval() / clearInterval()
The Application Cache





Inaccessible







Web Sockets
Web Data Storage

The DOM (thread-unsafe!)
The window objects
The document object
The parent object

Communicate with DOM by message
passing
Communication with Workers
 Use

postMessage() to send data to and from
Web Workers for cross-pages (sub windows /
internal frames) communication
 postMessage() can be used to send most
JavaScript objects, but Not JavaScript
Functions or Objects with Cyclic References,
since JSON doesn't support these
Web Workers
Stop Workers



Call worker.terminate() from the main page
Call self.close() inside of the worker itself
Handling Errors



e.message




e.filename




A human-readable error message
The name of the script file in which the error occurred

e.lineno


The line number of the script file on which the error occurred
Sub Web Workers
 Workers

have the ability to spawn sub
workers, but…




Sub-workers must be hosted within the same
origin as the parent page
The URIs for sub workers are resolved relative to
the parent worker's location rather than that of the
owning page
Sub Web Workers
Shared Web Workers
 Shared

Web Worker can be shared across
pages (popups / iframes) on the same origin
 Introduce the notion of ports that are used for
postMessage() communication
 Be useful for data synchronization among
multiple pages (or tabs) on the same origin or
to share a long-lived resource (like a
WebSocket) among several tabs
Shared Web Workers
Inline Web Workers


Inline Web Workers which are created in the same
web page context or on the fly





Page Inline Worker





Reduce the number of requests that the page perform
Create some functionality on the fly
The worker's code is created inline inside the web page
<script type="javascript/worker">

On The Fly Worker


The worker’s code is provided by an external source as
string
Inline Web Workers
Loading External Scripts
 Workers

have access to a importScripts API
which lets them import scripts into their scope




importScripts('script1.js');
importScripts('script2.js');
importScripts('script1.js', 'script2.js');

 Scripts

may be downloaded in any order, but
will be executed in the order in which you
pass the filenames
Use Cases


Performing computations in the background






Performing web I/O in the background







Code syntax highlighting
Real-time text formatting
Spell / Grammar checker
Pre-fetching and/or caching data
Background I/O or polling of web services
Concurrent requests against a local storage
Updating many rows of a local storage

Dividing tasks among multiple workers





Image processing
Image synthesize
Analyzing video or audio data
Processing large data sets
jQuery Plug-in






In Firefox, It can be sent the complex data via
postMessage()
In Chrome and Safari, It will handle only a string or
other simple data via postMessage()
Web Workers with jQuery Hive






Worker-to-worker direct messaging
Object, array, and String manipulation
Query JSON with JSONPath
Variable evaluation and logic control flow utilities
A syntax that jQuery developers will understand
Conclusion
 Demo




Demo 1
Demo 2
Demo 3

 Q&A

HTML5 Multithreading

  • 1.
  • 2.
    Agenda  Single  Threaded Model UnresponsiveScript  Multithreading    Web Workers (Dedicated) Sub Web Workers Shared Web Workers
  • 3.
  • 4.
    Single Threaded Model   JavaScriptin a browser executes on a Single Thread Asynchronous Events Timer Delay is Not Guaranteed!
  • 5.
    Unresponsive Script  Browser complainsa long-running script and ask user if it should be stopped
  • 6.
    Unresponsive Script  Solutions  setTimeout()   Use1ms timeout chunks cause task to complete slowly overall, but browser UI will remain responsive Web Workers  Web workers provide background thread support in the browser
  • 7.
  • 8.
    Web Workers     Dedicated WebWorkers Allow long-running script that are not interrupted by scripts that respond to clicks or other user interactions Allows long tasks to be executed without yielding to keep the page responsive Checking for Browser Support  Compatibility Tables  if (typeof(window.Worker) !== ‘undefined’) { // this browser supports web workers }
  • 9.
    Workers Environment  Accessible       The this/ self object (worker) The navigator object The read-only location object XMLHttpRequest setTimeout() / clearTimeout() setInterval() / clearInterval() The Application Cache    Inaccessible      Web Sockets Web Data Storage The DOM (thread-unsafe!) The window objects The document object The parent object Communicate with DOM by message passing
  • 10.
    Communication with Workers Use postMessage() to send data to and from Web Workers for cross-pages (sub windows / internal frames) communication  postMessage() can be used to send most JavaScript objects, but Not JavaScript Functions or Objects with Cyclic References, since JSON doesn't support these
  • 11.
  • 12.
    Stop Workers   Call worker.terminate()from the main page Call self.close() inside of the worker itself
  • 13.
    Handling Errors  e.message   e.filename   A human-readableerror message The name of the script file in which the error occurred e.lineno  The line number of the script file on which the error occurred
  • 14.
    Sub Web Workers Workers have the ability to spawn sub workers, but…   Sub-workers must be hosted within the same origin as the parent page The URIs for sub workers are resolved relative to the parent worker's location rather than that of the owning page
  • 15.
  • 16.
    Shared Web Workers Shared Web Worker can be shared across pages (popups / iframes) on the same origin  Introduce the notion of ports that are used for postMessage() communication  Be useful for data synchronization among multiple pages (or tabs) on the same origin or to share a long-lived resource (like a WebSocket) among several tabs
  • 17.
  • 18.
    Inline Web Workers  InlineWeb Workers which are created in the same web page context or on the fly    Page Inline Worker    Reduce the number of requests that the page perform Create some functionality on the fly The worker's code is created inline inside the web page <script type="javascript/worker"> On The Fly Worker  The worker’s code is provided by an external source as string
  • 19.
  • 20.
    Loading External Scripts Workers have access to a importScripts API which lets them import scripts into their scope   importScripts('script1.js'); importScripts('script2.js'); importScripts('script1.js', 'script2.js');  Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames
  • 21.
    Use Cases  Performing computationsin the background     Performing web I/O in the background      Code syntax highlighting Real-time text formatting Spell / Grammar checker Pre-fetching and/or caching data Background I/O or polling of web services Concurrent requests against a local storage Updating many rows of a local storage Dividing tasks among multiple workers     Image processing Image synthesize Analyzing video or audio data Processing large data sets
  • 22.
    jQuery Plug-in    In Firefox,It can be sent the complex data via postMessage() In Chrome and Safari, It will handle only a string or other simple data via postMessage() Web Workers with jQuery Hive      Worker-to-worker direct messaging Object, array, and String manipulation Query JSON with JSONPath Variable evaluation and logic control flow utilities A syntax that jQuery developers will understand
  • 23.

Editor's Notes