SlideShare a Scribd company logo
1 of 51
Web Worker in your
Angular Application
By :- Suresh Patidar
September 9, 2018
Target audience
This presentation is useful for people who are:
● Creating/defining architecture for their next
generation products.
● Product manager/owner, concerned about the
end user experience and customer
satisfaction.
● Using or planning to use Angular as a
framework for developing the front end of
their products.
● Web developers building high performance
web applications.
● Interested in knowing new web development
trends and how to incorporate some of them
into their products.
Assumption
This presentation assumes that you are already familiar
with web development technologies(HTML/CSS/JS/TS)
and architectures(SPA) and have some knowledge
about frameworks implementing these architectures
(like Angular, ReactJS etc.)
TOC
● What is Angular and what does it offer?
● What is Angular CLI?
● How to work with web worker in cli project?
● What other choices do we have?
● Example - Angular 5 with angular-cli 1.6.8
● Example - Angular 6 with angular-cli 6.1.5
Angular and it’s Offering
Angular
Angular is a platform that
makes it easy to build
applications with the web.
Angular empowers developers
to build applications that live on
the web, mobile, or the desktop.
● Develop across all platform by reusing your
code and building your apps for any
deployment target.
● Achieve maximum speed and performance
possible on the web platform today.
● Incredible tooling to build features quickly.
Key offering
Angular CLI
● A command line interface for building angular
applications
● Responsible for automating away many of
challenges and headaches of developers.
● Makes easier to get started and get moving
quickly with Angular.
Angular CLI
How to work with web
worker in CLI project?
● Angular framework supports running your whole application in Web
Worker.
● Extract webpack configuration file using “eject” feature of CLI-1.
● Install web worker bootstrap dependencies.
● Make changes in UI bootstrap logic. (app.module.ts, main.ts,
workerLoader.ts)
● Update webpack to build your web worker.
● This support require a thorough planning as your application should not
have any direct references to DOM, Window, document or parent in your
typescript code.
Source:- https://blog.angularindepth.com/angular-with-web-workers-step-by-step-dc11d5872135
Working with Web Worker in CLI-1 (Angular 5
or below) Projects
What other choices do
we have?
Few concerns that we may have with approach discussed in previous slides:
● I have performance problem in just a small part of the project and not the whole
application.
● I don’t want to run whole application in web worker.
● I don’t want to eject from CLI and own whole webpack configuration.
● I am not sure if my application is compatible to run in we web worker and also not in
a position to fix incompatibilities (if any).
● I want to have a better control on what to run and what not to run in web worker.
In order to address these concerns, let’s plan to implement web worker as an
independent piece of code and integrate the same with CLI and the
application.
In following slides we will create a sample application implementing web
worker, integrating it to CLI and finally to our application.
Other choices
Simple Example
Disclaimer
This example presents one of the way to integrate web worker in Angular application and may
not be the only and best way to do so. The way of integrations are largely depends on the
application need, use case and other external/internal environmental constraints. The example I
am going to create in subsequent slides is purely based on my online research and past
experience.
What are we going to implement?
In order to demonstrate the integration of web worker in Angular application, we
will create a simple angular app using angular-cli. The app will have only one
component created by default. We will add couple of interactive UI animations and
few buttons to trigger processing in web worker and non web worker mode and
feel the performance and responsiveness of the browser UI.
To mock the CPU intensive processing we will implement a simple function that
takes a duration as parameter and enter in a while loop for the given duration. It
returns the number of iterations done in the loop.
Angular version used for Example
01
We are going to implement this example using both Angular 5
and Angular 6.
We are doing this for both versions because of the difference in
the angular-cli used to create these projects. Angular 5
application is created using angular-cli version 1.6.8 and the
Angular 6 applications is created using angular-cli version 6.1.5.
The way projects are created and built using these CLIs are quite
different.
Feel free to refer only the example that matches your project
requirement and skip the other.
Development Environment Used
● Windows 10 pro 64 bit operating system
● NodeJS v8.9.3
● NPM v5.5.1
● Angular Cli v1.6.8 for example 1 and v6.5.8 for example 2
● Visual Studio Code v1.25.1
This is just an information about the environment used and you can always use
your own environment for the development, provided framework and libraries used
are compatible.
NGULAR 5 (5.2.0)
NGULAR CLI 1 (1.6.8)
First Implementation of the Example
Note:- Focus more on understanding of this example. You can download complete code
of this example from github:- https://github.com/patidar-suresh/angular5-webworker
Create new Angular 5 App using CLI
Open a command prompt from your working directory and
create new angular 5 application using command “ng new
angular5-webworker --style=scss”.
This command will create a directory named “angular5-
webworker”, download project structure and install all the
dependencies required for your project.
Let’s first create a folder structure for our worker. Create a folder called “worker” at same
level as “src”. This folder will hold all the code for workers implementation.
Folder structure for worker:
main.worker.ts
app.workers.ts
Topic?
cpu-
intensive.work
er.ts
image-
processing.w
orker.ts
Now create a file “main.worker.ts” as the first entry point for our worker. It create a new
instance of AppWorkers and listen for messages from parent. It also pass the received
messages to app workers for further processing.
main.worker.ts
app.workers.ts
Topic
?
cpu-
intensive.wo
rker.ts
image-
processing.wor
ker.ts
Create a file “app.workers.ts”. It will hold the logic to distribute the work based on topic. It
is also responsible to return the message back to the parent.
main.worker.ts
app.workers.ts
Topic
?
cpu-
intensive.wo
rker.ts
image-
processing.wor
ker.ts
Create a file “cpu-intensive.worker.ts” to implement our first worker which will hold the
logic to perform cpu intensive work by entering in a while loop for given duration.
main.worker.ts
app.workers.ts
Topic
?
cpu-
intensive.wo
rker.ts
image-
processing.wor
ker.ts
Create “worker-message.model.ts” and “worker-topic.constants.ts” under shared folder.
These are shared model and constants used across the workers and worker clients.
worker-message.model.ts
worker-topic.constants.ts
We are done with
creating worker code!!!
Now let’s configure
webpack to build it for us.
Create a custom webpack config file (webpack.worker.config.js) that will
build web worker code using angular-cli. You may notice that we asked
webpack to build and create bundle in “src/assets/workers” directory.
Modify package.json and add few scripts for development convenience. Here we are using node
module “concurrently” for watching worker changes concurrently with app code changes. Install
“concurrently” by running command “npm install concurrently --save-dev”
We are all set :)
Let’s start using web
worker in our application.
Create a service called “worker.service.ts” under src/app directory. This service will be
responsible for initializing web worker and delegating the work to it.
Modify app.module.ts to provide worker service.
Modify “app.component.html” and “app.component.scss” and add above html and scss content
to it. Here we have added an animated flying bird and input box to echo the message typed into
it. We also have buttons to start processing in different modes.
app.component.scss
app.component.html
Modify “app.component.ts” to add properties, logic and handlers. This component uses the
worker service to perform cpu intensive calculation in web worker. For non worker mode similar
calculation logic is coded in component itself.
Let’s start the application using command “npm start”. You will see a command output similar to
mentioned above. Open browser and enter http://localhost:4200 to see the application live.
Try run processing in different mode and experience the performance and responsiveness.
Complete code of this example is available at- https://github.com/patidar-suresh/angular5-
webworker
NGULAR 6 (6.1.0)
NGULAR CLI 6 (6.1.5)
Second Implementation of the
Example
Note:- Focus more on understanding of this example. You can download complete code
of this example from github:- https://github.com/patidar-suresh/angular6-webworker
Create new Angular 6 App using CLI
Open a command prompt from your working directory and
create new angular 6 application using command “ng new
angular6-webworker --style=scss”.
This command will create a directory named “angular6-
webworker”, download project structure and install all the
dependencies required for your project.
Since we don’t have any have changes in worker logic
between Angular 5 and Angular 6, so you can create the
worker same as mentioned in earlier slides:
● Create worker folder structure (Slide #21)
● Create main worker (Slide #22)
● Create app worker (Slide #23)
● Create cpu intensive worker (Slide #24)
● Create shared model and constants (Slide #25)
We have created worker
code!!!
Now let’s configure Angular
CLI to build it for us.
Before we start configuration, let’s see
what’s new in Angular Cli 6?
● Support for libraries and multiple applications
○ Create libraries of a set of component,directives, pipes and services to
share.
○ Create several applications in same cli project (called workspace)
● A new architecture
○ Broken down into small pieces
○ New “Architect” package
○ New configuration file (“angular.json”)
● New Schematics.
● Webpack 4 under the hood.
● Better error stacks and reduced installation time.
How to customize Angular CLI 6 build?
● In Angular cli 1.x we had “ng eject’ but in Angular cli 6 it has been
disabled temporarily.
● CLI 6 has new concept called builders. With builders we can customize
the build process.
● We can define our own builders or use one of the builder provided by
community.
Let’s modify “angular.json” and add builder (“build-worker” & “serve-worker”) for our worker code
by using angular builder (“@angular-devkit/build-angular:server”). Now running command “ng run
angular6-webworker:build-worker” should generate worker bundle in src/assets/workers.
Modify package.json and add few scripts for developer convenience. Here we are using node
module “concurrently” for watching worker changes concurrently with app code changes. Install
“concurrently” by running command “npm install concurrently --save-dev”
Since we neither changed worker logic nor its usage between
Angular 5 and Angular 6, so you can modify your app to use web
worker in similar way as done in earlier slides:
● Create worker service(Slide #30) , Few RXJS related changes to accommodate:
○ Replace all the rxjs imports with “import { Subject, Observable, Subscription,
fromEvent } from 'rxjs';”
○ Update workerPath to “assets/workers/main.js”
○ Change “Observable.fromEvent(“ to just “fromEvent(“
● Modify app module to provide service (Slide #31)
● Modify app component html and scss (Slide #32)
● Modify component ts file (Slide #33)
● Run the application using “npm start” (Slide #34)
Can’t see the result when you start
processing in web worker mode?
So let’s investigate...
Do you see some error in console like below image?
Some searching on google and stackoverflow, revealed that typescript(2.7.2)
is adding “exports” to the bundle file (main.js).
Older version of typescript(2.1.6) solved the exact same issue, but we don’t
have option to use the older version as Angular 6 requires the latest one.
Removing “exports” from the first line of main.js file, seems to be fixing this
issue. So let’s use this hack until this gets fixed in typescript.
But how do we implement this hack in an elegant way?
Angular CLI 6 Builders to Rescue!
Here is the implementation plan:
● Install “custom-webpack” builder.
● Install “replace-in-file-webpack-plugin”
● Create custom webpack config.
● Modify “angular.json” to use custom webpack config.
Install builder for custom-webpack by command “npm install @angular-builders/custom-
webpack --save-dev”. Also install replace-in-file-webpack plugin using command “npm install
replace-in-file-webpack-plugin --save-dev”
Create custom webpack file (webpack.webworker.config.js) in the root directory of your
application. In this additional configuration we just need to define what we need for extra
functionalities. Other default functionalities will take configuration from CLI automatically.
Modify “angular.json” and update the builders for worker to use custom-webpack builder and provide
appropriate configurations. You can optionally define “configurations” for “production” build as
needed. I have skipped them here.
Complete code of this example is available at- https://github.com/patidar-suresh/angular6-webworker
We are done with changes!
Run “npm start” and open url http://localhost:4200 in
the browser to access the application.
Note:- Make sure to get rid of the hack that we just implemented,
once you get a proper fix for typescript error.
Thank you!
Suresh Patidar
Email: suresh.patidar@gmail.com
Github: https://github.com/patidar-suresh
LinkedIn: www.linkedin.com/in/suresh-patidar-659a1950

More Related Content

What's hot

Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Kanika Gera
 
React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...Edureka!
 
Containers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatContainers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatAmazon Web Services
 
learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .paradisetechsoftsolutions
 
Introduction to Kubernetes
Introduction to KubernetesIntroduction to Kubernetes
Introduction to Kubernetesrajdeep
 
Service workers
Service workersService workers
Service workersjungkees
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questionsGoa App
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSHoang Long
 
Microservice Architecture | Microservices Tutorial for Beginners | Microservi...
Microservice Architecture | Microservices Tutorial for Beginners | Microservi...Microservice Architecture | Microservices Tutorial for Beginners | Microservi...
Microservice Architecture | Microservices Tutorial for Beginners | Microservi...Edureka!
 
Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...
Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...
Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...Amazon Web Services
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Microservices
MicroservicesMicroservices
MicroservicesSmartBear
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendSpike Brehm
 
Introduction to Docker Compose
Introduction to Docker ComposeIntroduction to Docker Compose
Introduction to Docker ComposeAjeet Singh Raina
 
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...Amazon Web Services
 

What's hot (20)

AWS MSP & Competency
AWS MSP & CompetencyAWS MSP & Competency
AWS MSP & Competency
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Progressive Web App
Progressive Web AppProgressive Web App
Progressive Web App
 
React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...React Interview Questions and Answers | React Tutorial | React Redux Online T...
React Interview Questions and Answers | React Tutorial | React Redux Online T...
 
Containers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatContainers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red Hat
 
learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .
 
Introduction to Kubernetes
Introduction to KubernetesIntroduction to Kubernetes
Introduction to Kubernetes
 
Service workers
Service workersService workers
Service workers
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Microservice Architecture | Microservices Tutorial for Beginners | Microservi...
Microservice Architecture | Microservices Tutorial for Beginners | Microservi...Microservice Architecture | Microservices Tutorial for Beginners | Microservi...
Microservice Architecture | Microservices Tutorial for Beginners | Microservi...
 
Camunda BPM 7.13 Webinar
Camunda BPM 7.13 WebinarCamunda BPM 7.13 Webinar
Camunda BPM 7.13 Webinar
 
Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...
Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...
Hands-on SaaS: Constructing multi-tenant solutions with AWS - SVC307 - New Yo...
 
Vue, vue router, vuex
Vue, vue router, vuexVue, vue router, vuex
Vue, vue router, vuex
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Microservices
MicroservicesMicroservices
Microservices
 
The Evolution of Airbnb's Frontend
The Evolution of Airbnb's FrontendThe Evolution of Airbnb's Frontend
The Evolution of Airbnb's Frontend
 
Angular 9
Angular 9 Angular 9
Angular 9
 
Introduction to Docker Compose
Introduction to Docker ComposeIntroduction to Docker Compose
Introduction to Docker Compose
 
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
SaaS Reference Architectures: Review of Real-World Patterns & Strategies (GPS...
 

Similar to Web worker in your angular application

Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshareSaleemMalik52
 
Django simplified : by weever mbakaya
Django simplified : by weever mbakayaDjango simplified : by weever mbakaya
Django simplified : by weever mbakayaMbakaya Kwatukha
 
White Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeWhite Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeHamida Rebai Trabelsi
 
Angular4 getting started
Angular4 getting startedAngular4 getting started
Angular4 getting startedTejinderMakkar
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsRapidValue
 
AOT(Ahead Of Time)
AOT(Ahead Of Time)AOT(Ahead Of Time)
AOT(Ahead Of Time)Questpond
 
ANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 schANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 schkannikadg
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
Angular 6 Training with project in hyderabad india
Angular 6 Training with project in hyderabad indiaAngular 6 Training with project in hyderabad india
Angular 6 Training with project in hyderabad indiaphp2ranjan
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - IntroductionWebStackAcademy
 
Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps Ahmed Bouchefra
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsWebStackAcademy
 
Angular.ppt
Angular.pptAngular.ppt
Angular.pptMytrux1
 
How create react app help in creating a new react applications
How create react app help in creating a new react applications How create react app help in creating a new react applications
How create react app help in creating a new react applications Concetto Labs
 
Angular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web ApplicationsAngular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web ApplicationsAlbiorix Technology
 
Introduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setupIntroduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setupAnsley Rodrigues
 

Similar to Web worker in your angular application (20)

Angular kickstart slideshare
Angular kickstart   slideshareAngular kickstart   slideshare
Angular kickstart slideshare
 
Angular
AngularAngular
Angular
 
Django simplified : by weever mbakaya
Django simplified : by weever mbakayaDjango simplified : by weever mbakaya
Django simplified : by weever mbakaya
 
White Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeWhite Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and Prime
 
Angular4 getting started
Angular4 getting startedAngular4 getting started
Angular4 getting started
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue Solutions
 
AOT(Ahead Of Time)
AOT(Ahead Of Time)AOT(Ahead Of Time)
AOT(Ahead Of Time)
 
Angular 2.0
Angular  2.0Angular  2.0
Angular 2.0
 
ANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 schANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 sch
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework
 
An Overview of Angular 4
An Overview of Angular 4 An Overview of Angular 4
An Overview of Angular 4
 
Angular 6 Training with project in hyderabad india
Angular 6 Training with project in hyderabad indiaAngular 6 Training with project in hyderabad india
Angular 6 Training with project in hyderabad india
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps Learn Angular 9/8 In Easy Steps
Learn Angular 9/8 In Easy Steps
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
How Does Angular Work?
How Does Angular Work?How Does Angular Work?
How Does Angular Work?
 
Angular.ppt
Angular.pptAngular.ppt
Angular.ppt
 
How create react app help in creating a new react applications
How create react app help in creating a new react applications How create react app help in creating a new react applications
How create react app help in creating a new react applications
 
Angular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web ApplicationsAngular Best Practices To Build Clean and Performant Web Applications
Angular Best Practices To Build Clean and Performant Web Applications
 
Introduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setupIntroduction to angular | Concepts and Environment setup
Introduction to angular | Concepts and Environment setup
 

More from Suresh Patidar

Conducting Effective Interviews
Conducting Effective InterviewsConducting Effective Interviews
Conducting Effective InterviewsSuresh Patidar
 
Conducting Good Interviews
Conducting Good InterviewsConducting Good Interviews
Conducting Good InterviewsSuresh Patidar
 
Developing high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web workerDeveloping high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web workerSuresh Patidar
 
Learning AngularJS - Complete coverage of AngularJS features and concepts
Learning AngularJS  - Complete coverage of AngularJS features and conceptsLearning AngularJS  - Complete coverage of AngularJS features and concepts
Learning AngularJS - Complete coverage of AngularJS features and conceptsSuresh Patidar
 
Introduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesIntroduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesSuresh Patidar
 
Building Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN StackBuilding Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN StackSuresh Patidar
 
Space-Based Architecture
Space-Based ArchitectureSpace-Based Architecture
Space-Based ArchitectureSuresh Patidar
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentSuresh Patidar
 

More from Suresh Patidar (8)

Conducting Effective Interviews
Conducting Effective InterviewsConducting Effective Interviews
Conducting Effective Interviews
 
Conducting Good Interviews
Conducting Good InterviewsConducting Good Interviews
Conducting Good Interviews
 
Developing high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web workerDeveloping high performance and responsive web apps using web worker
Developing high performance and responsive web apps using web worker
 
Learning AngularJS - Complete coverage of AngularJS features and concepts
Learning AngularJS  - Complete coverage of AngularJS features and conceptsLearning AngularJS  - Complete coverage of AngularJS features and concepts
Learning AngularJS - Complete coverage of AngularJS features and concepts
 
Introduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web TechnologiesIntroduction to Modern and Emerging Web Technologies
Introduction to Modern and Emerging Web Technologies
 
Building Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN StackBuilding Modern Web Apps with MEAN Stack
Building Modern Web Apps with MEAN Stack
 
Space-Based Architecture
Space-Based ArchitectureSpace-Based Architecture
Space-Based Architecture
 
Modern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web DevelopmentModern UI Architecture_ Trends and Technologies in Web Development
Modern UI Architecture_ Trends and Technologies in Web Development
 

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
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.comFatema Valibhai
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Recently uploaded (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
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
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

Web worker in your angular application

  • 1. Web Worker in your Angular Application By :- Suresh Patidar September 9, 2018
  • 2. Target audience This presentation is useful for people who are: ● Creating/defining architecture for their next generation products. ● Product manager/owner, concerned about the end user experience and customer satisfaction. ● Using or planning to use Angular as a framework for developing the front end of their products. ● Web developers building high performance web applications. ● Interested in knowing new web development trends and how to incorporate some of them into their products.
  • 3. Assumption This presentation assumes that you are already familiar with web development technologies(HTML/CSS/JS/TS) and architectures(SPA) and have some knowledge about frameworks implementing these architectures (like Angular, ReactJS etc.)
  • 4. TOC ● What is Angular and what does it offer? ● What is Angular CLI? ● How to work with web worker in cli project? ● What other choices do we have? ● Example - Angular 5 with angular-cli 1.6.8 ● Example - Angular 6 with angular-cli 6.1.5
  • 6. Angular Angular is a platform that makes it easy to build applications with the web. Angular empowers developers to build applications that live on the web, mobile, or the desktop.
  • 7. ● Develop across all platform by reusing your code and building your apps for any deployment target. ● Achieve maximum speed and performance possible on the web platform today. ● Incredible tooling to build features quickly. Key offering
  • 9. ● A command line interface for building angular applications ● Responsible for automating away many of challenges and headaches of developers. ● Makes easier to get started and get moving quickly with Angular. Angular CLI
  • 10. How to work with web worker in CLI project?
  • 11. ● Angular framework supports running your whole application in Web Worker. ● Extract webpack configuration file using “eject” feature of CLI-1. ● Install web worker bootstrap dependencies. ● Make changes in UI bootstrap logic. (app.module.ts, main.ts, workerLoader.ts) ● Update webpack to build your web worker. ● This support require a thorough planning as your application should not have any direct references to DOM, Window, document or parent in your typescript code. Source:- https://blog.angularindepth.com/angular-with-web-workers-step-by-step-dc11d5872135 Working with Web Worker in CLI-1 (Angular 5 or below) Projects
  • 12. What other choices do we have?
  • 13. Few concerns that we may have with approach discussed in previous slides: ● I have performance problem in just a small part of the project and not the whole application. ● I don’t want to run whole application in web worker. ● I don’t want to eject from CLI and own whole webpack configuration. ● I am not sure if my application is compatible to run in we web worker and also not in a position to fix incompatibilities (if any). ● I want to have a better control on what to run and what not to run in web worker. In order to address these concerns, let’s plan to implement web worker as an independent piece of code and integrate the same with CLI and the application. In following slides we will create a sample application implementing web worker, integrating it to CLI and finally to our application. Other choices
  • 15. Disclaimer This example presents one of the way to integrate web worker in Angular application and may not be the only and best way to do so. The way of integrations are largely depends on the application need, use case and other external/internal environmental constraints. The example I am going to create in subsequent slides is purely based on my online research and past experience.
  • 16. What are we going to implement? In order to demonstrate the integration of web worker in Angular application, we will create a simple angular app using angular-cli. The app will have only one component created by default. We will add couple of interactive UI animations and few buttons to trigger processing in web worker and non web worker mode and feel the performance and responsiveness of the browser UI. To mock the CPU intensive processing we will implement a simple function that takes a duration as parameter and enter in a while loop for the given duration. It returns the number of iterations done in the loop.
  • 17. Angular version used for Example 01 We are going to implement this example using both Angular 5 and Angular 6. We are doing this for both versions because of the difference in the angular-cli used to create these projects. Angular 5 application is created using angular-cli version 1.6.8 and the Angular 6 applications is created using angular-cli version 6.1.5. The way projects are created and built using these CLIs are quite different. Feel free to refer only the example that matches your project requirement and skip the other.
  • 18. Development Environment Used ● Windows 10 pro 64 bit operating system ● NodeJS v8.9.3 ● NPM v5.5.1 ● Angular Cli v1.6.8 for example 1 and v6.5.8 for example 2 ● Visual Studio Code v1.25.1 This is just an information about the environment used and you can always use your own environment for the development, provided framework and libraries used are compatible.
  • 19. NGULAR 5 (5.2.0) NGULAR CLI 1 (1.6.8) First Implementation of the Example Note:- Focus more on understanding of this example. You can download complete code of this example from github:- https://github.com/patidar-suresh/angular5-webworker
  • 20. Create new Angular 5 App using CLI Open a command prompt from your working directory and create new angular 5 application using command “ng new angular5-webworker --style=scss”. This command will create a directory named “angular5- webworker”, download project structure and install all the dependencies required for your project.
  • 21. Let’s first create a folder structure for our worker. Create a folder called “worker” at same level as “src”. This folder will hold all the code for workers implementation. Folder structure for worker: main.worker.ts app.workers.ts Topic? cpu- intensive.work er.ts image- processing.w orker.ts
  • 22. Now create a file “main.worker.ts” as the first entry point for our worker. It create a new instance of AppWorkers and listen for messages from parent. It also pass the received messages to app workers for further processing. main.worker.ts app.workers.ts Topic ? cpu- intensive.wo rker.ts image- processing.wor ker.ts
  • 23. Create a file “app.workers.ts”. It will hold the logic to distribute the work based on topic. It is also responsible to return the message back to the parent. main.worker.ts app.workers.ts Topic ? cpu- intensive.wo rker.ts image- processing.wor ker.ts
  • 24. Create a file “cpu-intensive.worker.ts” to implement our first worker which will hold the logic to perform cpu intensive work by entering in a while loop for given duration. main.worker.ts app.workers.ts Topic ? cpu- intensive.wo rker.ts image- processing.wor ker.ts
  • 25. Create “worker-message.model.ts” and “worker-topic.constants.ts” under shared folder. These are shared model and constants used across the workers and worker clients. worker-message.model.ts worker-topic.constants.ts
  • 26. We are done with creating worker code!!! Now let’s configure webpack to build it for us.
  • 27. Create a custom webpack config file (webpack.worker.config.js) that will build web worker code using angular-cli. You may notice that we asked webpack to build and create bundle in “src/assets/workers” directory.
  • 28. Modify package.json and add few scripts for development convenience. Here we are using node module “concurrently” for watching worker changes concurrently with app code changes. Install “concurrently” by running command “npm install concurrently --save-dev”
  • 29. We are all set :) Let’s start using web worker in our application.
  • 30. Create a service called “worker.service.ts” under src/app directory. This service will be responsible for initializing web worker and delegating the work to it.
  • 31. Modify app.module.ts to provide worker service.
  • 32. Modify “app.component.html” and “app.component.scss” and add above html and scss content to it. Here we have added an animated flying bird and input box to echo the message typed into it. We also have buttons to start processing in different modes. app.component.scss app.component.html
  • 33. Modify “app.component.ts” to add properties, logic and handlers. This component uses the worker service to perform cpu intensive calculation in web worker. For non worker mode similar calculation logic is coded in component itself.
  • 34. Let’s start the application using command “npm start”. You will see a command output similar to mentioned above. Open browser and enter http://localhost:4200 to see the application live. Try run processing in different mode and experience the performance and responsiveness. Complete code of this example is available at- https://github.com/patidar-suresh/angular5- webworker
  • 35. NGULAR 6 (6.1.0) NGULAR CLI 6 (6.1.5) Second Implementation of the Example Note:- Focus more on understanding of this example. You can download complete code of this example from github:- https://github.com/patidar-suresh/angular6-webworker
  • 36. Create new Angular 6 App using CLI Open a command prompt from your working directory and create new angular 6 application using command “ng new angular6-webworker --style=scss”. This command will create a directory named “angular6- webworker”, download project structure and install all the dependencies required for your project.
  • 37. Since we don’t have any have changes in worker logic between Angular 5 and Angular 6, so you can create the worker same as mentioned in earlier slides: ● Create worker folder structure (Slide #21) ● Create main worker (Slide #22) ● Create app worker (Slide #23) ● Create cpu intensive worker (Slide #24) ● Create shared model and constants (Slide #25)
  • 38. We have created worker code!!! Now let’s configure Angular CLI to build it for us.
  • 39. Before we start configuration, let’s see what’s new in Angular Cli 6? ● Support for libraries and multiple applications ○ Create libraries of a set of component,directives, pipes and services to share. ○ Create several applications in same cli project (called workspace) ● A new architecture ○ Broken down into small pieces ○ New “Architect” package ○ New configuration file (“angular.json”) ● New Schematics. ● Webpack 4 under the hood. ● Better error stacks and reduced installation time.
  • 40. How to customize Angular CLI 6 build? ● In Angular cli 1.x we had “ng eject’ but in Angular cli 6 it has been disabled temporarily. ● CLI 6 has new concept called builders. With builders we can customize the build process. ● We can define our own builders or use one of the builder provided by community.
  • 41. Let’s modify “angular.json” and add builder (“build-worker” & “serve-worker”) for our worker code by using angular builder (“@angular-devkit/build-angular:server”). Now running command “ng run angular6-webworker:build-worker” should generate worker bundle in src/assets/workers.
  • 42. Modify package.json and add few scripts for developer convenience. Here we are using node module “concurrently” for watching worker changes concurrently with app code changes. Install “concurrently” by running command “npm install concurrently --save-dev”
  • 43. Since we neither changed worker logic nor its usage between Angular 5 and Angular 6, so you can modify your app to use web worker in similar way as done in earlier slides: ● Create worker service(Slide #30) , Few RXJS related changes to accommodate: ○ Replace all the rxjs imports with “import { Subject, Observable, Subscription, fromEvent } from 'rxjs';” ○ Update workerPath to “assets/workers/main.js” ○ Change “Observable.fromEvent(“ to just “fromEvent(“ ● Modify app module to provide service (Slide #31) ● Modify app component html and scss (Slide #32) ● Modify component ts file (Slide #33) ● Run the application using “npm start” (Slide #34)
  • 44. Can’t see the result when you start processing in web worker mode? So let’s investigate...
  • 45. Do you see some error in console like below image? Some searching on google and stackoverflow, revealed that typescript(2.7.2) is adding “exports” to the bundle file (main.js). Older version of typescript(2.1.6) solved the exact same issue, but we don’t have option to use the older version as Angular 6 requires the latest one. Removing “exports” from the first line of main.js file, seems to be fixing this issue. So let’s use this hack until this gets fixed in typescript.
  • 46. But how do we implement this hack in an elegant way? Angular CLI 6 Builders to Rescue! Here is the implementation plan: ● Install “custom-webpack” builder. ● Install “replace-in-file-webpack-plugin” ● Create custom webpack config. ● Modify “angular.json” to use custom webpack config.
  • 47. Install builder for custom-webpack by command “npm install @angular-builders/custom- webpack --save-dev”. Also install replace-in-file-webpack plugin using command “npm install replace-in-file-webpack-plugin --save-dev”
  • 48. Create custom webpack file (webpack.webworker.config.js) in the root directory of your application. In this additional configuration we just need to define what we need for extra functionalities. Other default functionalities will take configuration from CLI automatically.
  • 49. Modify “angular.json” and update the builders for worker to use custom-webpack builder and provide appropriate configurations. You can optionally define “configurations” for “production” build as needed. I have skipped them here. Complete code of this example is available at- https://github.com/patidar-suresh/angular6-webworker
  • 50. We are done with changes! Run “npm start” and open url http://localhost:4200 in the browser to access the application. Note:- Make sure to get rid of the hack that we just implemented, once you get a proper fix for typescript error.
  • 51. Thank you! Suresh Patidar Email: suresh.patidar@gmail.com Github: https://github.com/patidar-suresh LinkedIn: www.linkedin.com/in/suresh-patidar-659a1950