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

More Related Content

KEY
Getting Started with HTML 5 Web workers
PDF
Web workers
PDF
Web Workers
PPTX
Heuristics to scale your framework
PDF
General Assembly Workshop: Advanced JavaScript
PDF
Building Isomorphic Apps (JSConf.Asia 2014)
PPTX
HTML5 Web Workers-unleashed
PDF
JSConf US 2014: Building Isomorphic Apps
Getting Started with HTML 5 Web workers
Web workers
Web Workers
Heuristics to scale your framework
General Assembly Workshop: Advanced JavaScript
Building Isomorphic Apps (JSConf.Asia 2014)
HTML5 Web Workers-unleashed
JSConf US 2014: Building Isomorphic Apps

What's hot (20)

PPTX
ASP.NET MVC and ajax
PPTX
Node.js
PDF
Isomorphic JavaScript: #DevBeat Master Class
PPTX
Modern Applications With Asp.net Core 5 and Vue JS 3
PDF
AJAX in ASP.NET
PDF
Workshop 21: React Router
PPT
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
PDF
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
PPTX
Spring Boot Update
PDF
Isomorphic JavaScript with Nashorn
PPT
Active Server Page(ASP)
PPTX
Workshop Intro: FrontEnd General Overview
PPTX
Web driver training
PDF
Isomorphic web application
PDF
A Django like messages framework for Tornado
PDF
Selenium webdriver
PDF
Ch5 beeing an application
PDF
Integrating Browserify with Sprockets
PPT
Servlet 01
ASP.NET MVC and ajax
Node.js
Isomorphic JavaScript: #DevBeat Master Class
Modern Applications With Asp.net Core 5 and Vue JS 3
AJAX in ASP.NET
Workshop 21: React Router
SenchaCon 2016: Expect the Unexpected - Dealing with Errors in Web Apps
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Spring Boot Update
Isomorphic JavaScript with Nashorn
Active Server Page(ASP)
Workshop Intro: FrontEnd General Overview
Web driver training
Isomorphic web application
A Django like messages framework for Tornado
Selenium webdriver
Ch5 beeing an application
Integrating Browserify with Sprockets
Servlet 01
Ad

Viewers also liked (9)

PPT
Md09 multithreading
PPT
Async IO and Multithreading explained
PPT
Database connectivity and web technologies
PPT
Java Input Output and File Handling
PPT
Java And Multithreading
PPT
JDBC Java Database Connectivity
PPSX
JDBC: java DataBase connectivity
PPT
Java multi threading
Md09 multithreading
Async IO and Multithreading explained
Database connectivity and web technologies
Java Input Output and File Handling
Java And Multithreading
JDBC Java Database Connectivity
JDBC: java DataBase connectivity
Java multi threading
Ad

Similar to HTML5 Multithreading (20)

PDF
Web workers
PDF
C sharp and asp.net interview questions
PPTX
Html web workers
DOC
Java script by Act Academy
PPTX
PPTX
AJppt.pptx
PPTX
webworkers
PPT
Lessons from the Trenches: Engineering Great AJAX Experiences
PPT
Lessons
DOC
Basics java scripts
PDF
High Performance JavaScript (YUIConf 2010)
PDF
Meebo performance ny_web_performance
PPTX
Introduction to JQuery, ASP.NET MVC and Silverlight
PDF
JAVA SCRIPT
PPTX
Client side scripting using Javascript
ODP
Introduction to Seam Applications
ODP
Introduction to seam_applications_formated
ODP
Introduction to seam_applications_formated
Web workers
C sharp and asp.net interview questions
Html web workers
Java script by Act Academy
AJppt.pptx
webworkers
Lessons from the Trenches: Engineering Great AJAX Experiences
Lessons
Basics java scripts
High Performance JavaScript (YUIConf 2010)
Meebo performance ny_web_performance
Introduction to JQuery, ASP.NET MVC and Silverlight
JAVA SCRIPT
Client side scripting using Javascript
Introduction to Seam Applications
Introduction to seam_applications_formated
Introduction to seam_applications_formated

More from Allan Huang (20)

PPTX
Concurrency in Java
PPTX
Build, logging, and unit test tools
PPTX
Drools
PPT
Java JSON Parser Comparison
PPT
Netty 4-based RPC System Development
PPT
eSobi Website Multilayered Architecture
PPT
Java New Evolution
PPT
Tomcat New Evolution
PPT
JQuery New Evolution
PPT
Responsive Web Design
PPT
Boilerpipe Integration And Improvement
PPT
YQL Case Study
PPT
Build Cross-Platform Mobile Application with PhoneGap
PPT
HTML5 Offline Web Application
PPT
HTML5 Data Storage
PPT
Java Script Patterns
PPT
Weighted feed recommand
PPT
Web Crawler
PPT
eSobi Site Initiation
PPT
Architecture of eSobi club based on J2EE
Concurrency in Java
Build, logging, and unit test tools
Drools
Java JSON Parser Comparison
Netty 4-based RPC System Development
eSobi Website Multilayered Architecture
Java New Evolution
Tomcat New Evolution
JQuery New Evolution
Responsive Web Design
Boilerpipe Integration And Improvement
YQL Case Study
Build Cross-Platform Mobile Application with PhoneGap
HTML5 Offline Web Application
HTML5 Data Storage
Java Script Patterns
Weighted feed recommand
Web Crawler
eSobi Site Initiation
Architecture of eSobi club based on J2EE

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation theory and applications.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Electronic commerce courselecture one. Pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Encapsulation_ Review paper, used for researhc scholars
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Mobile App Security Testing_ A Comprehensive Guide.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Machine Learning_overview_presentation.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation theory and applications.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Network Security Unit 5.pdf for BCA BBA.
Programs and apps: productivity, graphics, security and other tools
20250228 LYD VKU AI Blended-Learning.pptx
A comparative analysis of optical character recognition models for extracting...
Dropbox Q2 2025 Financial Results & Investor Presentation
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Agricultural_Statistics_at_a_Glance_2022_0.pdf

HTML5 Multithreading

  • 2. Agenda  Single  Threaded Model Unresponsive Script  Multithreading    Web Workers (Dedicated) Sub Web Workers Shared Web Workers
  • 4. Single Threaded Model   JavaScript in a browser executes on a Single Thread Asynchronous Events Timer Delay is Not Guaranteed!
  • 5. Unresponsive Script  Browser complains a long-running script and ask user if it should be stopped
  • 6. 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
  • 8. 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 }
  • 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
  • 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-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
  • 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
  • 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
  • 18. 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
  • 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 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
  • 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

Editor's Notes