SlideShare uma empresa Scribd logo
1 de 49
Baixar para ler offline
The easy way
BOOST YOUR ANGULAR
APP WITH WEB WORKERS
blog.enriqueoriol.com
medium.com/@enriqueoriol
twitter.com/Enrique_oriol
Enrique Oriol
Wearing multiple hats at Narada Robotics startup, from coding to whatever else…
SW engineer (mobile & frontend) / blogger / Udemy trainer
IN LOVE WITH ANGULAR & IONIC
Enrique Oriol
CTO @ Narada Robotics
blog.enriqueoriol.com
medium.com/@enriqueoriol
twitter.com/Enrique_oriol
ANGULAR WEB WORKERS
Summary
JS IS SINGLE THREADED01
MULTITHREADED DEVICES02
WEB WORKERS HISTORY03
ANGULAR WEB WORKERS04
HANDS ON CODE05
QUESTIONS06
JAVASCRIPT NATURE IS...
Asynchronous
Single threaded
ANGULAR WEB WORKERS 5
JS is async & Single threaded
import api from './controllers/api';
var login = (user, pwd) => {
api.post('login', {user:user, pwd:pwd})
.then(response => {
if(response.code == 200){
console.log("Congrats! you're in");
}
else{
console.log("Login error");
}
});
console.log("let's try to log-in");
}
Program thread
1
@Enrique_oriol
ANGULAR WEB WORKERS 6
import api from './controllers/api';
var login = (user, pwd) => {
api.post('login', {user:user, pwd:pwd})
.then(response => {
if(response.code == 200){
console.log("Congrats! you're in");
}
else{
console.log("Login error");
}
});
console.log("let's try to log-in");
}
JS is async & Single threaded
Program thread
1
Somewhere
else
A
S
Y
N
C
Waiting for
response
@Enrique_oriol
ANGULAR WEB WORKERS 7
import api from './controllers/api';
var login = (user, pwd) => {
api.post('login', {user:user, pwd:pwd})
.then(response => {
if(response.code == 200){
console.log("Congrats! you're in");
}
else{
console.log("Login error");
}
});
console.log("let's try to log-in");
}
JS is async & Single threaded
Program thread
1
Somewhere
else
A
S
Y
N
C
2
Waiting for
response
@Enrique_oriol
ANGULAR WEB WORKERS 9
JS is async & Single threaded
import api from './controllers/api';
var login = (user, pwd) => {
api.post('login', {user:user, pwd:pwd})
.then(response => {
if(response.code == 200){
console.log("Congrats! you're in");
}
else{
console.log("Login error");
}
});
console.log("let's try to log-in");
}
Program thread
Somewhere
else
1
2
3
A
S
Y
N
C
Waiting for
response
@Enrique_oriol
MULTI THREADED
WORLD
ANGULAR WEB WORKERS 11
MULTI THREADED WORLD
Multi-core processors
@Enrique_oriol
ANGULAR WEB WORKERS 12
MULTI THREADED WORLD
Also in smartphones
@Enrique_oriol
ANGULAR WEB WORKERS 13
MULTI THREADED WORLD
CoreCoreCoreCore
Our devices (simplified)
@Enrique_oriol
ANGULAR WEB WORKERS 14
CoreCoreCoreCore
JS
world
Javascript (simplified)
@Enrique_oriol
MULTI THREADED WORLD
WEB
WORKERS
A first contact
ANGULAR WEB WORKERS 16
WEB WORKERS
HTML5 compatible
INDEPENDENT
FILE
ISOLATED
PROCESS
MESSAGE BASED
COMMUNICATION
RUN TASKS IN
PARALLEL
@Enrique_oriol
ANGULAR WEB WORKERS 17
WEB WORKERS
The web worker
myWorker.js
var someVeryHardTask = param => {/*...some stuff*/}
self.addEventListener('message', e => {
let result = someVeryHardTask(e.data);
self.postMessage(result);
}, false);
@Enrique_oriol
ANGULAR WEB WORKERS 18
WEB WORKERS
The web worker
myWorker.js
var someVeryHardTask = param => {/*...some stuff*/}
self.addEventListener('message', e => {
let result = someVeryHardTask(e.data);
self.postMessage(result);
}, false);
@Enrique_oriol
ANGULAR WEB WORKERS 19
WEB WORKERS
The web worker
myWorker.js
var someVeryHardTask = param => {/*...some stuff*/}
self.addEventListener('message', e => {
let result = someVeryHardTask(e.data);
self.postMessage(result);
}, false);
@Enrique_oriol
ANGULAR WEB WORKERS 20
WEB WORKERS
The web worker
myWorker.js
var someVeryHardTask = param => {/*...some stuff*/}
self.addEventListener('message', e => {
let result = someVeryHardTask(e.data);
self.postMessage(result);
}, false);
@Enrique_oriol
ANGULAR WEB WORKERS 21
WEB WORKERS
The “main thread”
main.js
var worker = new Worker('myWorker.js');
worker.onmessage = event => {
console.log(result, event.data);
}
worker.postMessage("someData");
@Enrique_oriol
ANGULAR WEB WORKERS 22
WEB WORKERS
The “main thread”
main.js
var worker = new Worker('myWorker.js');
worker.onmessage = event => {
console.log(result, event.data);
}
worker.postMessage("someData");
@Enrique_oriol
ANGULAR WEB WORKERS 23
WEB WORKERS
The “main thread”
main.js
var worker = new Worker('myWorker.js');
worker.onmessage = event => {
console.log(result, event.data);
}
worker.postMessage("someData");
@Enrique_oriol
ANGULAR WEB WORKERS 24
WEB WORKERS
Thread 2 (myWorker.js)Thread 1 (main.js)
The big picture
var worker=new Worker('myWorker.js');
worker.postMessage("st");
console.log(result)
someVeryHardTask(e.data);
self.postMessage(result);
self.onmessage(...)self.onmessage(...)
@Enrique_oriol
ANGULAR WEB WORKERS 25
CAUTION
Is this enough?
This idea is extremely hot
@Enrique_oriol
ANGULAR WEB WORKERS 26
WEB WORKERS
● LOTS OF TASKS ?
○ INFINITE SWITCH STATEMENT?
○ SEVERAL WORKERS?
○ TOO MUCH MESSAGING STUFF…
● Heavy DOM?
● CONSUMING UI?
Is this enough ?
@Enrique_oriol
ANGULAR WEB WORKERS 27
WEB WORKERS
Native apps approach
DO NOT BLOCK THE UI THREAD
@Enrique_oriol
ANGULAR WEB WORKERS 28
WEB WORKERS
Native apps approach: do not block the UI thread
Other stuff threadsUI Thread (main thread)
@Enrique_oriol
Someone in Angular
ANGULAR WEB WORKERS 30
CAUTION
Why don’t we run
all the business logic of our app,
directly,
inside a web worker?
This idea is extremely hot
@Enrique_oriol
ANGULAR WEB WORKERS 31
CAUTION
COOL!
This idea is extremely hot
@Enrique_oriol
ANGULAR WEB WORKERS 32
CAUTION
But…
how does it work?
This idea is extremely hot
@Enrique_oriol
ANGULAR WEB WORKERS 33
REGULAR
Angular bootstrap
index.html
bundle.js
App component
bootstrapModule(AppModule)
Using platform-browser
<script></script>
@Enrique_oriol
ANGULAR WEB WORKERS 34
WEB WORKERS
Angular bootstrap
index.html
bundle.js
worker.js
bootstrapWorkerUI(‘worker.js’)
Using platform-webworker
<script></script>
App component
bootstrapModule(AppModule)
Using platform-worker
UI thread Worker thread
@Enrique_oriol
ANGULAR WEB WORKERS 35
WEB WORKERS
Angular approach (simplified) idea
Worker threadUI Thread
postMessage(“data”)
UI event (click, …)
postMessage(“call component method”)
Binded data updated
Run
business
logic
@Enrique_oriol
ANGULAR WEB WORKERS 36
WEB WORKERS
Angular approach
Worker threadUI Thread
postMessage(“data”)
UI event (click, …)
postMessage(“call component method”)
Binded data updated
Run
business
logic
Angular handles this for you
@Enrique_oriol
ANGULAR WEB WORKERS 37
BENEFITS
Running Angular with Web Workers
● Components remain the same
● Full access to Angular APIs
● Web Worker code can always run without Web Workers
@Enrique_oriol
ANGULAR WEB WORKERS 38
LIMITATIONS
Running Angular with Web Workers
● No DOM access
● DOM manipulation should be done by
○ Data bindings
○ Using Renderer
@Enrique_oriol
ANGULAR WEB WORKERS 39
LIMITATIONS
Where can you use Web Workers (April 2017)
@Enrique_oriol
DEMO TIME
Wanna play with code ?
ANGULAR WEB WORKERS 41
You can download code here:
https://github.com/kaikcreator/angular-cli-web-worker
And play it live here:
https://kaikcreator.github.io/angular-cli-web-worker/
EXAMPLE APP
Factorial app demo example
@Enrique_oriol
ANGULAR WEB WORKERS 42
CAUTION
You convinced me...
Can you guide me step-by-step?
This idea is extremely hot
@Enrique_oriol
ANGULAR WEB WORKERS 43
CAUTION
For sure!
Take any existing angular CLI
project and...
This idea is extremely hot
@Enrique_oriol
ANGULAR WEB WORKERS 44
Extract webpack file
@Enrique_oriol
MIGRATION GUIDE
From Angular CLI generated project
ng eject
npm installRun new dependencies generated by CLI
npm install --save @angular/platform-webworker @angular/platform-webworker-dynamic
Install webworker bootstrap dependencies
ANGULAR WEB WORKERS 45
Changes in app.module.ts
@Enrique_oriol
MIGRATION GUIDE
From Angular CLI generated project
BrowserModuleReplace
WorkerAppModulewith @angular/platform-webworkerfrom
ANGULAR WEB WORKERS 46
Changes in main.ts
@Enrique_oriol
MIGRATION GUIDE
From Angular CLI generated project
bootstrapModule()Replace
bootstrapWorkerUi(‘webworker.bundle.js’)
@angular/platform-webworkerfrom
with
ANGULAR WEB WORKERS 47
MIGRATION GUIDE
From Angular CLI generated project
Create file workerLoader.ts
import 'polyfills.ts';
import '@angular/core';
import '@angular/common';
import { platformWorkerAppDynamic } from '@angular/platform-webworker-dynamic';
import { AppModule } from './app/app.module';
platformWorkerAppDynamic().bootstrapModule(AppModule);
@Enrique_oriol
ANGULAR WEB WORKERS 48
Update webpack to build your webworker
@Enrique_oriol
MIGRATION GUIDE
From Angular CLI generated project
webworkerAdd entry point workerLoader.tsfor
Update HtmlWebpackPlugin to exclude webworker
Update CommonChunksPlugin inline chunk to prevent including webworker
‘entryModule’: ‘app/app.module#AppModule’Update AotPlugin with
THANKS!
blog.enriqueoriol.com
medium.com/@enriqueoriol
twitter.com/Enrique_oriol
Enrique Oriol
U like what you read?
SHARE IT ;)

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Zenly - Reverse geocoding
Zenly - Reverse geocodingZenly - Reverse geocoding
Zenly - Reverse geocoding
 
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
 
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
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32
 
Leaving Interface Builder Behind
Leaving Interface Builder BehindLeaving Interface Builder Behind
Leaving Interface Builder Behind
 
AngularJs
AngularJsAngularJs
AngularJs
 
Solid angular
Solid angularSolid angular
Solid angular
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Rapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirageRapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirage
 
An introduction to Ember.js
An introduction to Ember.jsAn introduction to Ember.js
An introduction to Ember.js
 
Testing Ember Apps: Managing Dependency
Testing Ember Apps: Managing DependencyTesting Ember Apps: Managing Dependency
Testing Ember Apps: Managing Dependency
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 

Semelhante a Boost your angular app with web workers

Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4
Akhil Mittal
 

Semelhante a Boost your angular app with web workers (20)

Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
Electron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easyElectron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easy
 
Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020
 
Submit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdfSubmit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdf
 
Angularjs
AngularjsAngularjs
Angularjs
 
JavaScript Web Workers
JavaScript Web WorkersJavaScript Web Workers
JavaScript Web Workers
 
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
 
Diving into VS 2015 Day4
Diving into VS 2015 Day4Diving into VS 2015 Day4
Diving into VS 2015 Day4
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
 
Meteor.js Workshop by Dopravo
Meteor.js Workshop by DopravoMeteor.js Workshop by Dopravo
Meteor.js Workshop by Dopravo
 
BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!BP204 - Take a REST and put your data to work with APIs!
BP204 - Take a REST and put your data to work with APIs!
 
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
How React Native, Appium and me made each other shine @ContinuousDeliveryAmst...
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
AngularJS 101
AngularJS 101AngularJS 101
AngularJS 101
 
API Technical Writing
API Technical WritingAPI Technical Writing
API Technical Writing
 
Telerik AppBuilder Presentation for TelerikNEXT Conference
Telerik AppBuilder Presentation for TelerikNEXT ConferenceTelerik AppBuilder Presentation for TelerikNEXT Conference
Telerik AppBuilder Presentation for TelerikNEXT Conference
 
Concurrent networking - made easy
Concurrent networking - made easyConcurrent networking - made easy
Concurrent networking - made easy
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Serverless Single Page Apps with React and Redux at ItCamp 2017
Serverless Single Page Apps with React and Redux at ItCamp 2017Serverless Single Page Apps with React and Redux at ItCamp 2017
Serverless Single Page Apps with React and Redux at ItCamp 2017
 
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 

Boost your angular app with web workers

  • 1. The easy way BOOST YOUR ANGULAR APP WITH WEB WORKERS blog.enriqueoriol.com medium.com/@enriqueoriol twitter.com/Enrique_oriol Enrique Oriol
  • 2. Wearing multiple hats at Narada Robotics startup, from coding to whatever else… SW engineer (mobile & frontend) / blogger / Udemy trainer IN LOVE WITH ANGULAR & IONIC Enrique Oriol CTO @ Narada Robotics blog.enriqueoriol.com medium.com/@enriqueoriol twitter.com/Enrique_oriol
  • 3. ANGULAR WEB WORKERS Summary JS IS SINGLE THREADED01 MULTITHREADED DEVICES02 WEB WORKERS HISTORY03 ANGULAR WEB WORKERS04 HANDS ON CODE05 QUESTIONS06
  • 5. ANGULAR WEB WORKERS 5 JS is async & Single threaded import api from './controllers/api'; var login = (user, pwd) => { api.post('login', {user:user, pwd:pwd}) .then(response => { if(response.code == 200){ console.log("Congrats! you're in"); } else{ console.log("Login error"); } }); console.log("let's try to log-in"); } Program thread 1 @Enrique_oriol
  • 6. ANGULAR WEB WORKERS 6 import api from './controllers/api'; var login = (user, pwd) => { api.post('login', {user:user, pwd:pwd}) .then(response => { if(response.code == 200){ console.log("Congrats! you're in"); } else{ console.log("Login error"); } }); console.log("let's try to log-in"); } JS is async & Single threaded Program thread 1 Somewhere else A S Y N C Waiting for response @Enrique_oriol
  • 7. ANGULAR WEB WORKERS 7 import api from './controllers/api'; var login = (user, pwd) => { api.post('login', {user:user, pwd:pwd}) .then(response => { if(response.code == 200){ console.log("Congrats! you're in"); } else{ console.log("Login error"); } }); console.log("let's try to log-in"); } JS is async & Single threaded Program thread 1 Somewhere else A S Y N C 2 Waiting for response @Enrique_oriol
  • 8. ANGULAR WEB WORKERS 9 JS is async & Single threaded import api from './controllers/api'; var login = (user, pwd) => { api.post('login', {user:user, pwd:pwd}) .then(response => { if(response.code == 200){ console.log("Congrats! you're in"); } else{ console.log("Login error"); } }); console.log("let's try to log-in"); } Program thread Somewhere else 1 2 3 A S Y N C Waiting for response @Enrique_oriol
  • 10. ANGULAR WEB WORKERS 11 MULTI THREADED WORLD Multi-core processors @Enrique_oriol
  • 11. ANGULAR WEB WORKERS 12 MULTI THREADED WORLD Also in smartphones @Enrique_oriol
  • 12. ANGULAR WEB WORKERS 13 MULTI THREADED WORLD CoreCoreCoreCore Our devices (simplified) @Enrique_oriol
  • 13. ANGULAR WEB WORKERS 14 CoreCoreCoreCore JS world Javascript (simplified) @Enrique_oriol MULTI THREADED WORLD
  • 15. ANGULAR WEB WORKERS 16 WEB WORKERS HTML5 compatible INDEPENDENT FILE ISOLATED PROCESS MESSAGE BASED COMMUNICATION RUN TASKS IN PARALLEL @Enrique_oriol
  • 16. ANGULAR WEB WORKERS 17 WEB WORKERS The web worker myWorker.js var someVeryHardTask = param => {/*...some stuff*/} self.addEventListener('message', e => { let result = someVeryHardTask(e.data); self.postMessage(result); }, false); @Enrique_oriol
  • 17. ANGULAR WEB WORKERS 18 WEB WORKERS The web worker myWorker.js var someVeryHardTask = param => {/*...some stuff*/} self.addEventListener('message', e => { let result = someVeryHardTask(e.data); self.postMessage(result); }, false); @Enrique_oriol
  • 18. ANGULAR WEB WORKERS 19 WEB WORKERS The web worker myWorker.js var someVeryHardTask = param => {/*...some stuff*/} self.addEventListener('message', e => { let result = someVeryHardTask(e.data); self.postMessage(result); }, false); @Enrique_oriol
  • 19. ANGULAR WEB WORKERS 20 WEB WORKERS The web worker myWorker.js var someVeryHardTask = param => {/*...some stuff*/} self.addEventListener('message', e => { let result = someVeryHardTask(e.data); self.postMessage(result); }, false); @Enrique_oriol
  • 20. ANGULAR WEB WORKERS 21 WEB WORKERS The “main thread” main.js var worker = new Worker('myWorker.js'); worker.onmessage = event => { console.log(result, event.data); } worker.postMessage("someData"); @Enrique_oriol
  • 21. ANGULAR WEB WORKERS 22 WEB WORKERS The “main thread” main.js var worker = new Worker('myWorker.js'); worker.onmessage = event => { console.log(result, event.data); } worker.postMessage("someData"); @Enrique_oriol
  • 22. ANGULAR WEB WORKERS 23 WEB WORKERS The “main thread” main.js var worker = new Worker('myWorker.js'); worker.onmessage = event => { console.log(result, event.data); } worker.postMessage("someData"); @Enrique_oriol
  • 23. ANGULAR WEB WORKERS 24 WEB WORKERS Thread 2 (myWorker.js)Thread 1 (main.js) The big picture var worker=new Worker('myWorker.js'); worker.postMessage("st"); console.log(result) someVeryHardTask(e.data); self.postMessage(result); self.onmessage(...)self.onmessage(...) @Enrique_oriol
  • 24. ANGULAR WEB WORKERS 25 CAUTION Is this enough? This idea is extremely hot @Enrique_oriol
  • 25. ANGULAR WEB WORKERS 26 WEB WORKERS ● LOTS OF TASKS ? ○ INFINITE SWITCH STATEMENT? ○ SEVERAL WORKERS? ○ TOO MUCH MESSAGING STUFF… ● Heavy DOM? ● CONSUMING UI? Is this enough ? @Enrique_oriol
  • 26. ANGULAR WEB WORKERS 27 WEB WORKERS Native apps approach DO NOT BLOCK THE UI THREAD @Enrique_oriol
  • 27. ANGULAR WEB WORKERS 28 WEB WORKERS Native apps approach: do not block the UI thread Other stuff threadsUI Thread (main thread) @Enrique_oriol
  • 29. ANGULAR WEB WORKERS 30 CAUTION Why don’t we run all the business logic of our app, directly, inside a web worker? This idea is extremely hot @Enrique_oriol
  • 30. ANGULAR WEB WORKERS 31 CAUTION COOL! This idea is extremely hot @Enrique_oriol
  • 31. ANGULAR WEB WORKERS 32 CAUTION But… how does it work? This idea is extremely hot @Enrique_oriol
  • 32. ANGULAR WEB WORKERS 33 REGULAR Angular bootstrap index.html bundle.js App component bootstrapModule(AppModule) Using platform-browser <script></script> @Enrique_oriol
  • 33. ANGULAR WEB WORKERS 34 WEB WORKERS Angular bootstrap index.html bundle.js worker.js bootstrapWorkerUI(‘worker.js’) Using platform-webworker <script></script> App component bootstrapModule(AppModule) Using platform-worker UI thread Worker thread @Enrique_oriol
  • 34. ANGULAR WEB WORKERS 35 WEB WORKERS Angular approach (simplified) idea Worker threadUI Thread postMessage(“data”) UI event (click, …) postMessage(“call component method”) Binded data updated Run business logic @Enrique_oriol
  • 35. ANGULAR WEB WORKERS 36 WEB WORKERS Angular approach Worker threadUI Thread postMessage(“data”) UI event (click, …) postMessage(“call component method”) Binded data updated Run business logic Angular handles this for you @Enrique_oriol
  • 36. ANGULAR WEB WORKERS 37 BENEFITS Running Angular with Web Workers ● Components remain the same ● Full access to Angular APIs ● Web Worker code can always run without Web Workers @Enrique_oriol
  • 37. ANGULAR WEB WORKERS 38 LIMITATIONS Running Angular with Web Workers ● No DOM access ● DOM manipulation should be done by ○ Data bindings ○ Using Renderer @Enrique_oriol
  • 38. ANGULAR WEB WORKERS 39 LIMITATIONS Where can you use Web Workers (April 2017) @Enrique_oriol
  • 39. DEMO TIME Wanna play with code ?
  • 40. ANGULAR WEB WORKERS 41 You can download code here: https://github.com/kaikcreator/angular-cli-web-worker And play it live here: https://kaikcreator.github.io/angular-cli-web-worker/ EXAMPLE APP Factorial app demo example @Enrique_oriol
  • 41. ANGULAR WEB WORKERS 42 CAUTION You convinced me... Can you guide me step-by-step? This idea is extremely hot @Enrique_oriol
  • 42. ANGULAR WEB WORKERS 43 CAUTION For sure! Take any existing angular CLI project and... This idea is extremely hot @Enrique_oriol
  • 43. ANGULAR WEB WORKERS 44 Extract webpack file @Enrique_oriol MIGRATION GUIDE From Angular CLI generated project ng eject npm installRun new dependencies generated by CLI npm install --save @angular/platform-webworker @angular/platform-webworker-dynamic Install webworker bootstrap dependencies
  • 44. ANGULAR WEB WORKERS 45 Changes in app.module.ts @Enrique_oriol MIGRATION GUIDE From Angular CLI generated project BrowserModuleReplace WorkerAppModulewith @angular/platform-webworkerfrom
  • 45. ANGULAR WEB WORKERS 46 Changes in main.ts @Enrique_oriol MIGRATION GUIDE From Angular CLI generated project bootstrapModule()Replace bootstrapWorkerUi(‘webworker.bundle.js’) @angular/platform-webworkerfrom with
  • 46. ANGULAR WEB WORKERS 47 MIGRATION GUIDE From Angular CLI generated project Create file workerLoader.ts import 'polyfills.ts'; import '@angular/core'; import '@angular/common'; import { platformWorkerAppDynamic } from '@angular/platform-webworker-dynamic'; import { AppModule } from './app/app.module'; platformWorkerAppDynamic().bootstrapModule(AppModule); @Enrique_oriol
  • 47. ANGULAR WEB WORKERS 48 Update webpack to build your webworker @Enrique_oriol MIGRATION GUIDE From Angular CLI generated project webworkerAdd entry point workerLoader.tsfor Update HtmlWebpackPlugin to exclude webworker Update CommonChunksPlugin inline chunk to prevent including webworker ‘entryModule’: ‘app/app.module#AppModule’Update AotPlugin with
  • 48.