SlideShare a Scribd company logo
var worker = new Worker(‘MyWork.js');worker.addEventListener('message', function(e) {document.getElementById(‘heading').textContent(e.data);}, false);worker.postMessage(‘WEB WORKERS'); WEB WORKERS1Amitesh Madhur  (amitesh@yahoo-inc.com)(Exceptional Performance, Bangalore)onmessage = function(e) {postMessage(e.data);}
for(;;;){	// Perceived performance of the UI}2Why Web Workers?JavaScript should not execute for longer than 100 milliseconds to ensure responsive UI. My recommendation, though, is to keep JavaScript under 50 milliseconds at a time, because why even try to get close to that? - Nicholas ZakasUI Blocked for 100 milliseconds == Perceived  										performance 	 								  page is slow50 milliseconds….
3What is Web Worker?serializeunserializeworker.postMessage(obj || str)HeavyComputationFormatDataMAIN PAGEMAIN PAGEself.postMessage(obj || str)MAIN PAGEserializeunserialize
Without Web WorkersWith Web WorkersWhat are Web WorkersWorker EnvironmentSubworkers/DelegationInline WorkerRestrictionsBrowser SupportUse casesDemoAGENDA4onmessage = fn{}setTimeout();worker.postMessage('Hello World');worker.postMessage(obj);self.postMessage(e.data);
Without Web Workers5ChromeInternet ExplorerFirefox
With Web Workers6ChromeInternet ExplorerFirefox
What are Web Workers?Scripts running in background.Heavy Weight Scripts. 7
What are Web Workers?8myworker.js// create web workerworker.postMessage({‘cmd’:gen_num});self.onmessage = fn(e){}worker.onerror = fn(e){   // e.lineno   // e.filename   // e.message}// task completedself.postMessage(arrayOfRandomNum);worker.terminate();worker.onmessage = fn(e){   // update DOM with e.data}
Difference from other approach.How different from setTimeout?How different from AJAX?9
So what does Worker look like?10Main Page// Check if workers are supported.if (typeof(Worker) == "undefined") {     document.getElementById(‘support’).textContent = ‘Your browser does not  support Web Workers’; 	return false;} // worker object var worker = new Worker('worker.js');              // post message to workerworker.postMessage(‘Are you there?’);// error handling worker.onerror = function(event){     console.log(event.message + ‘ in file = ’ + event.filename + ‘ at line #’                 + event.lineno ); }; // on message handlerworker.onmessage = function (event)  {      document.getElementById('result').textContent = event.data;} 12345
So what does Worker look like?11worker.jsself.onmessage = function(event){postMessage(event.data + ‘ Worker says: Yes I am here.’);}ORself.addEventListener('message', function(e) {self.postMessage(event.data +‘ Worker says: Yes I am here.’);}, false);12
Worker Environment12No BOMNo DOM!parentsetTimeout, setInterval
navigator object
location object (read-only)
XMLHttpRequest
Spawning other web workersSubworker/Delegation13Ability to spawn child workersBreaks up huge task into smaller chunksSub workers should be in hosted in the same domainLocation of sub worker file is relative to parent worker (and not main page).
Subworker/Delegation14Parent Workerself.onmessage = function(event){varnum_workers = 4; // total sub workersvarpending_workers = num_workers; // loop though the sub-workers	for (vari = 0; i < num_workers; i++) {var worker = new Worker('subworker.js');worker.postMessage(event.data);// on message worker.onmessage = function(event) {varstr += event.data; // collect data pending_workers -= 1; // workers pending// case: all response collected then post to main page           if (pending_workers == 0) self.postMessage(str);        }	 // on message sub-worker end	} // loop end}1234
Subworker/Delegation15subworker.jsonmessage = function(event){postMessage(event.data + ‘ Sub Worker says: Yes I am here.’);}
Inline worker16Worker script on the fly Without creating separate worker fileBlobBuilder interface
Inline worker17Worker script on the fly Without creating separate worker fileBlobBuilder interfacevar bb = new BlobBuilder();bb.append("onmessage = function(e) { postMessage('msg            from worker'); }");varblobURL = window.URL.createObjectURL(bb.getBlob());var worker = new Worker(blobURL);worker.postMessage('Hello'); // post message to start worker// on messageworker.onmessage = function(e) {// e.data == 'msg from worker'};
Restrictions18!file:// (chrome)http: | https: && data: | javascript:
Ad

More Related Content

What's hot (20)

Service workers
Service workersService workers
Service workers
jungkees
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
Caldera Labs
 
JavaScript Web Workers
JavaScript Web WorkersJavaScript Web Workers
JavaScript Web Workers
Tobias Pfeiffer
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker Presentation
Kyle Dorman
 
React, Flux and a little bit of Redux
React, Flux and a little bit of ReduxReact, Flux and a little bit of Redux
React, Flux and a little bit of Redux
Ny Fanilo Andrianjafy, B.Eng.
 
Ember.js for Big Profit
Ember.js for Big ProfitEmber.js for Big Profit
Ember.js for Big Profit
CodeCore
 
Service workers
Service workersService workers
Service workers
Pavel Zhytko
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work manager
bhatnagar.gaurav83
 
Getting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workersGetting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workers
Flumes
 
Java script+mvc+with+emberjs
Java script+mvc+with+emberjsJava script+mvc+with+emberjs
Java script+mvc+with+emberjs
ji guang
 
Abstracting Just Enough
Abstracting Just EnoughAbstracting Just Enough
Abstracting Just Enough
jlongster2
 
JS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & RoutesJS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & Routes
Nick Dreckshage
 
Workmanager PPTX
Workmanager PPTXWorkmanager PPTX
Workmanager PPTX
Himanshu Singh
 
PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽
Anna Su
 
Introduction to Celery
Introduction to CeleryIntroduction to Celery
Introduction to Celery
Chathuranga Bandara
 
Automating boring tasks with Powershell
Automating boring tasks with PowershellAutomating boring tasks with Powershell
Automating boring tasks with Powershell
Alban Gérôme
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
Stephen Young
 
ReactJS
ReactJSReactJS
ReactJS
Kamlesh Singh
 
Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)
Anna Schneider
 
Service workers
Service workersService workers
Service workers
jungkees
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
Caldera Labs
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker Presentation
Kyle Dorman
 
Ember.js for Big Profit
Ember.js for Big ProfitEmber.js for Big Profit
Ember.js for Big Profit
CodeCore
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work manager
bhatnagar.gaurav83
 
Getting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workersGetting Started with HTML 5 Web workers
Getting Started with HTML 5 Web workers
Flumes
 
Java script+mvc+with+emberjs
Java script+mvc+with+emberjsJava script+mvc+with+emberjs
Java script+mvc+with+emberjs
ji guang
 
Abstracting Just Enough
Abstracting Just EnoughAbstracting Just Enough
Abstracting Just Enough
jlongster2
 
JS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & RoutesJS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & Routes
Nick Dreckshage
 
PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽
Anna Su
 
Automating boring tasks with Powershell
Automating boring tasks with PowershellAutomating boring tasks with Powershell
Automating boring tasks with Powershell
Alban Gérôme
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
Stephen Young
 
Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)
Anna Schneider
 

Similar to Amitesh Madhur - Web workers, HTML 5 (20)

Practical Celery
Practical CeleryPractical Celery
Practical Celery
Cameron Maske
 
Service worker: discover the next web game changer
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changer
Sandro Paganotti
 
2015 05 27 JSConf - concurrency and parallelism final
2015 05 27   JSConf - concurrency and parallelism final2015 05 27   JSConf - concurrency and parallelism final
2015 05 27 JSConf - concurrency and parallelism final
Naveed Ihsanullah
 
Munit junit test case
Munit junit test caseMunit junit test case
Munit junit test case
prudhvivreddy
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)
lyonjug
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Building Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devicesBuilding Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devices
Windows Developer
 
New improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiNew improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, Helsinki
Robert Nyman
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
Celery with python
Celery with pythonCelery with python
Celery with python
Alexandre González Rodríguez
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
bloodredsun
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
Glenn Stovall
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
dion
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
Rebecca Murphey
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
DrupalCon jQuery
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQuery
Nathan Smith
 
Service worker: discover the next web game changer
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changer
Sandro Paganotti
 
2015 05 27 JSConf - concurrency and parallelism final
2015 05 27   JSConf - concurrency and parallelism final2015 05 27   JSConf - concurrency and parallelism final
2015 05 27 JSConf - concurrency and parallelism final
Naveed Ihsanullah
 
Munit junit test case
Munit junit test caseMunit junit test case
Munit junit test case
prudhvivreddy
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)Spring Batch Workshop (advanced)
Spring Batch Workshop (advanced)
lyonjug
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Building Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devicesBuilding Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devices
Windows Developer
 
New improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiNew improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, Helsinki
Robert Nyman
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
bloodredsun
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
Glenn Stovall
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
dion
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
Rebecca Murphey
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Ad

Recently uploaded (20)

Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdfComputer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
fizarcse
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
DNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in NepalDNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in Nepal
ICT Frame Magazine Pvt. Ltd.
 
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More MachinesRefactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Leon Anavi
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Building a research repository that works by Clare Cady
Building a research repository that works by Clare CadyBuilding a research repository that works by Clare Cady
Building a research repository that works by Clare Cady
UXPA Boston
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
Google DeepMind’s New AI Coding Agent AlphaEvolve.pdf
Google DeepMind’s New AI Coding Agent AlphaEvolve.pdfGoogle DeepMind’s New AI Coding Agent AlphaEvolve.pdf
Google DeepMind’s New AI Coding Agent AlphaEvolve.pdf
derrickjswork
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdfComputer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
fizarcse
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More MachinesRefactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Leon Anavi
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Building a research repository that works by Clare Cady
Building a research repository that works by Clare CadyBuilding a research repository that works by Clare Cady
Building a research repository that works by Clare Cady
UXPA Boston
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
Google DeepMind’s New AI Coding Agent AlphaEvolve.pdf
Google DeepMind’s New AI Coding Agent AlphaEvolve.pdfGoogle DeepMind’s New AI Coding Agent AlphaEvolve.pdf
Google DeepMind’s New AI Coding Agent AlphaEvolve.pdf
derrickjswork
 
Ad

Amitesh Madhur - Web workers, HTML 5

  • 1. var worker = new Worker(‘MyWork.js');worker.addEventListener('message', function(e) {document.getElementById(‘heading').textContent(e.data);}, false);worker.postMessage(‘WEB WORKERS'); WEB WORKERS1Amitesh Madhur (amitesh@yahoo-inc.com)(Exceptional Performance, Bangalore)onmessage = function(e) {postMessage(e.data);}
  • 2. for(;;;){ // Perceived performance of the UI}2Why Web Workers?JavaScript should not execute for longer than 100 milliseconds to ensure responsive UI. My recommendation, though, is to keep JavaScript under 50 milliseconds at a time, because why even try to get close to that? - Nicholas ZakasUI Blocked for 100 milliseconds == Perceived performance page is slow50 milliseconds….
  • 3. 3What is Web Worker?serializeunserializeworker.postMessage(obj || str)HeavyComputationFormatDataMAIN PAGEMAIN PAGEself.postMessage(obj || str)MAIN PAGEserializeunserialize
  • 4. Without Web WorkersWith Web WorkersWhat are Web WorkersWorker EnvironmentSubworkers/DelegationInline WorkerRestrictionsBrowser SupportUse casesDemoAGENDA4onmessage = fn{}setTimeout();worker.postMessage('Hello World');worker.postMessage(obj);self.postMessage(e.data);
  • 7. What are Web Workers?Scripts running in background.Heavy Weight Scripts. 7
  • 8. What are Web Workers?8myworker.js// create web workerworker.postMessage({‘cmd’:gen_num});self.onmessage = fn(e){}worker.onerror = fn(e){ // e.lineno // e.filename // e.message}// task completedself.postMessage(arrayOfRandomNum);worker.terminate();worker.onmessage = fn(e){ // update DOM with e.data}
  • 9. Difference from other approach.How different from setTimeout?How different from AJAX?9
  • 10. So what does Worker look like?10Main Page// Check if workers are supported.if (typeof(Worker) == "undefined") {     document.getElementById(‘support’).textContent = ‘Your browser does not  support Web Workers’; return false;} // worker object var worker = new Worker('worker.js');              // post message to workerworker.postMessage(‘Are you there?’);// error handling worker.onerror = function(event){     console.log(event.message + ‘ in file = ’ + event.filename + ‘ at line #’  + event.lineno ); }; // on message handlerworker.onmessage = function (event)  {      document.getElementById('result').textContent = event.data;} 12345
  • 11. So what does Worker look like?11worker.jsself.onmessage = function(event){postMessage(event.data + ‘ Worker says: Yes I am here.’);}ORself.addEventListener('message', function(e) {self.postMessage(event.data +‘ Worker says: Yes I am here.’);}, false);12
  • 12. Worker Environment12No BOMNo DOM!parentsetTimeout, setInterval
  • 16. Spawning other web workersSubworker/Delegation13Ability to spawn child workersBreaks up huge task into smaller chunksSub workers should be in hosted in the same domainLocation of sub worker file is relative to parent worker (and not main page).
  • 17. Subworker/Delegation14Parent Workerself.onmessage = function(event){varnum_workers = 4; // total sub workersvarpending_workers = num_workers; // loop though the sub-workers for (vari = 0; i < num_workers; i++) {var worker = new Worker('subworker.js');worker.postMessage(event.data);// on message worker.onmessage = function(event) {varstr += event.data; // collect data pending_workers -= 1; // workers pending// case: all response collected then post to main page if (pending_workers == 0) self.postMessage(str); } // on message sub-worker end } // loop end}1234
  • 19. Inline worker16Worker script on the fly Without creating separate worker fileBlobBuilder interface
  • 20. Inline worker17Worker script on the fly Without creating separate worker fileBlobBuilder interfacevar bb = new BlobBuilder();bb.append("onmessage = function(e) { postMessage('msg from worker'); }");varblobURL = window.URL.createObjectURL(bb.getBlob());var worker = new Worker(blobURL);worker.postMessage('Hello'); // post message to start worker// on messageworker.onmessage = function(e) {// e.data == 'msg from worker'};
  • 21. Restrictions18!file:// (chrome)http: | https: && data: | javascript:
  • 23. Use Cases20Prefetching and/or caching data for later useCode syntax highlighting or other real-time text formattingSpell checkerBackground I/O or polling of webservicesProcessing large arrays or JSON responses
  • 24. var worker = new Worker(‘MyWork.js');worker.addEventListener('message', function(e) {document.getElementById(‘heading').textContent(e.data);}, false);worker.postMessage(‘DEMO'); DEMO21onmessage = function(e) {postMessage(e.data);}

Editor's Notes

  • #14: Workers can delegate task to sub workers. For example, if a worker is performing very intensive task of updating 10,00,000 of records in database, it can spawn, let’s say , 10 sub workers and delegate a chunk of work to each one of these. These workers will run in parallel to perform the task given to them.
  • #17: If a worker need not be present in a separate javascript file, it can be created inline to the main script.
  • #20: Worker is supported in Firefox 3.5 and above, Chrome 4.0 and above, Safari 4.0 and above, Opera 10.6 and above. Workers are not supported in Internet Explorer.
  • #21: So what kind app would utilize web workers? Unfortunately, web workers are still relatively new and the majority of samples/tutorials out there involve computing prime numbers. Although that isn&apos;t very interesting, it&apos;s useful for understanding the concepts of web workers. Here are a few more ideas to get your brain churning:Prefetching and/or caching data for later useCode syntax highlighting or other real-time text formattingSpell checkerAnalyzing video or audio dataBackground I/O or polling of webservicesProcessing large arrays or humungous JSON responsesImage filtering in &lt;canvas&gt;Updating many rows of a local web database
  翻译: