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

PPTX
Introduction to Cosmos DB Presentation.pptx
Knoldus Inc.
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
Web Worker, Service Worker and Worklets
Keshav Gupta
 
PPTX
Angular overview
Thanvilahari
 
PDF
20200803 - Serverless with AWS @ HELTECH
Marcia Villalba
 
PDF
Microservices Design Patterns | Edureka
Edureka!
 
PDF
Measuring the Performance of Single Page Applications
Nicholas Jansma
 
PPTX
Java Spring
AathikaJava
 
Introduction to Cosmos DB Presentation.pptx
Knoldus Inc.
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Web Worker, Service Worker and Worklets
Keshav Gupta
 
Angular overview
Thanvilahari
 
20200803 - Serverless with AWS @ HELTECH
Marcia Villalba
 
Microservices Design Patterns | Edureka
Edureka!
 
Measuring the Performance of Single Page Applications
Nicholas Jansma
 
Java Spring
AathikaJava
 

What's hot (20)

PPTX
Consuming Restful APIs using Swagger v2.0
Pece Nikolovski
 
PPTX
Angular interview questions
Goa App
 
PDF
Building a Modern Security Engineering Organization
Zane Lackey
 
PPTX
Agile process (Scrum Framework)
Jakir Hosen Khan
 
PPTX
Spring boot
Pradeep Shanmugam
 
PPTX
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
PDF
Aem dispatcher – tips & tricks
Ashokkumar T A
 
PPT
Spring Core
Pushan Bhattacharya
 
PDF
JavaScript Promises
Derek Willian Stavis
 
PDF
Simple IO Monad in 'Functional Programming in Scala'
Philip Schwarz
 
PDF
Angular 10 course_content
NAVEENSAGGAM1
 
PDF
Angular & RXJS: examples and use cases
Fabio Biondi
 
PPTX
Agile Marketing Methodologies: Scrum and Kanban
Marsden Marketing
 
ODP
Getting access to Lantronix devices: exploring treasures of 77FEh at Confiden...
Vlatko Kosturjak
 
PPT
Agile overview
Benny Zangiri
 
PDF
Html5 notes for professionals
Zafer Galip Ozberk
 
PDF
angular fundamentals.pdf
NuttavutThongjor1
 
PDF
[AWS Dev Day] 인공지능 / 기계 학습 | 기계 학습 싸고 빠르게 하는 방법 - Amazon SageMaker 편 - 김필호 AW...
Amazon Web Services Korea
 
PPTX
Introduction to Spring Framework
Serhat Can
 
PDF
SI 화면테스트(단위) 가이드
SangIn Choung
 
Consuming Restful APIs using Swagger v2.0
Pece Nikolovski
 
Angular interview questions
Goa App
 
Building a Modern Security Engineering Organization
Zane Lackey
 
Agile process (Scrum Framework)
Jakir Hosen Khan
 
Spring boot
Pradeep Shanmugam
 
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
Aem dispatcher – tips & tricks
Ashokkumar T A
 
Spring Core
Pushan Bhattacharya
 
JavaScript Promises
Derek Willian Stavis
 
Simple IO Monad in 'Functional Programming in Scala'
Philip Schwarz
 
Angular 10 course_content
NAVEENSAGGAM1
 
Angular & RXJS: examples and use cases
Fabio Biondi
 
Agile Marketing Methodologies: Scrum and Kanban
Marsden Marketing
 
Getting access to Lantronix devices: exploring treasures of 77FEh at Confiden...
Vlatko Kosturjak
 
Agile overview
Benny Zangiri
 
Html5 notes for professionals
Zafer Galip Ozberk
 
angular fundamentals.pdf
NuttavutThongjor1
 
[AWS Dev Day] 인공지능 / 기계 학습 | 기계 학습 싸고 빠르게 하는 방법 - Amazon SageMaker 편 - 김필호 AW...
Amazon Web Services Korea
 
Introduction to Spring Framework
Serhat Can
 
SI 화면테스트(단위) 가이드
SangIn Choung
 
Ad

Similar to Web worker in your angular application (20)

PDF
Boost your angular app with web workers
Enrique Oriol Bermúdez
 
PPTX
NodeJS Concurrency
pgriess
 
PDF
Modern UI Development With Node.js
Ryan Anklam
 
PDF
Treinamento frontend
Adrian Caetano
 
PDF
How to build a website that works without internet using angular, service wor...
Tomiwa Ademidun
 
PDF
Web workers
Surbhi Mathur
 
PDF
Web workers
Surbhi Mathur
 
PPTX
webworkers
Asanka Indrajith
 
PPTX
Html web workers
AbhishekMondal42
 
PDF
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Ivan Loire
 
PDF
2013 jsdc webworker
Bingo Yang
 
PPTX
How NOT to write in Node.js
Piotr Pelczar
 
PDF
Node, can you even in CPU intensive operations?
The Software House
 
PPTX
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
PDF
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
Tech in Asia ID
 
PPTX
Node.js Anti Patterns
Ben Hall
 
PDF
Workers of the web - BrazilJS 2013
Thibault Imbert
 
PPTX
Scalable server component using NodeJS & ExpressJS
Andhy Koesnandar
 
PPTX
Workers
Adrian Caetano
 
PDF
Parallel development of Web Apps | Codesushi - Gliwice 2017
Krzysztof (Chris) Ozog
 
Boost your angular app with web workers
Enrique Oriol Bermúdez
 
NodeJS Concurrency
pgriess
 
Modern UI Development With Node.js
Ryan Anklam
 
Treinamento frontend
Adrian Caetano
 
How to build a website that works without internet using angular, service wor...
Tomiwa Ademidun
 
Web workers
Surbhi Mathur
 
Web workers
Surbhi Mathur
 
webworkers
Asanka Indrajith
 
Html web workers
AbhishekMondal42
 
Building web apps with node.js, socket.io, knockout.js and zombie.js - Codemo...
Ivan Loire
 
2013 jsdc webworker
Bingo Yang
 
How NOT to write in Node.js
Piotr Pelczar
 
Node, can you even in CPU intensive operations?
The Software House
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
Tech in Asia ID
 
Node.js Anti Patterns
Ben Hall
 
Workers of the web - BrazilJS 2013
Thibault Imbert
 
Scalable server component using NodeJS & ExpressJS
Andhy Koesnandar
 
Parallel development of Web Apps | Codesushi - Gliwice 2017
Krzysztof (Chris) Ozog
 
Ad

More from Suresh Patidar (8)

PPTX
Conducting Effective Interviews
Suresh Patidar
 
PPTX
Conducting Good Interviews
Suresh Patidar
 
PPTX
Developing high performance and responsive web apps using web worker
Suresh Patidar
 
PPTX
Learning AngularJS - Complete coverage of AngularJS features and concepts
Suresh Patidar
 
PPTX
Introduction to Modern and Emerging Web Technologies
Suresh Patidar
 
PPTX
Building Modern Web Apps with MEAN Stack
Suresh Patidar
 
PDF
Space-Based Architecture
Suresh Patidar
 
PDF
Modern UI Architecture_ Trends and Technologies in Web Development
Suresh Patidar
 
Conducting Effective Interviews
Suresh Patidar
 
Conducting Good Interviews
Suresh Patidar
 
Developing high performance and responsive web apps using web worker
Suresh Patidar
 
Learning AngularJS - Complete coverage of AngularJS features and concepts
Suresh Patidar
 
Introduction to Modern and Emerging Web Technologies
Suresh Patidar
 
Building Modern Web Apps with MEAN Stack
Suresh Patidar
 
Space-Based Architecture
Suresh Patidar
 
Modern UI Architecture_ Trends and Technologies in Web Development
Suresh Patidar
 

Recently uploaded (20)

PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
PDF
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
TestNG for Java Testing and Automation testing
ssuser0213cb
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPTX
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
Become an Agentblazer Champion Challenge
Dele Amefo
 
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Presentation about variables and constant.pptx
safalsingh810
 
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
Community & News Update Q2 Meet Up 2025
VictoriaMetrics
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
TestNG for Java Testing and Automation testing
ssuser0213cb
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Presentation about variables and constant.pptx
kr2589474
 
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Become an Agentblazer Champion Challenge
Dele Amefo
 

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: [email protected] Github: https://github.com/patidar-suresh LinkedIn: www.linkedin.com/in/suresh-patidar-659a1950