SlideShare une entreprise Scribd logo
1  sur  39
Developing High Performance and Responsive Web
Applications using Web Worker
By:- Suresh Patidar
2nd September 2018
Who am I?
My name is Suresh Patidar and I’m from Pune,
India.
I work for Calsoft Inc. full-time as Senior Architect
where I design architecture and solution for
products in Storage, Networking, Virtualization,
Cloud, IOT and ML domain.
I’m primarily a UI/UX person and works extensively
in web technologies and frameworks like
HTML5/CSS3, JavaScript, TypeScript, Angular, React,
Bootstrap, Backbone, NodeJS etc.
Agenda
● What is web application performance?
● Why should we care about web application performance?
● Some of best practices to optimize page load time.
● What is a responsive web application?
● General problem with web applications.
● Web Workers to rescue.
● Benefits of Web Workers.
● Challenges with Web Workers.
● Browser support.
● A simple example.
What is web application performance?
“Web performance refers to the speed in
which web pages are downloaded and
displayed on the user’s browser”
- From Wikipedia
“The delay perceived by the web application
user between an action(e.g. Click) and a
meaningful response”
- My definition
Performance Metrics
● Response Time -
○ How long it takes to process a request
● Throughput
○ Number of requests that the application can process within defined time interval
● System Availability
○ Percentage of the application’s run time minus the time application can’t be accessed
● Responsiveness
○ How quickly the system acknowledge a request as opposed to processing it
● Request Rate
○ Metric to track the number of concurrent users.
Performance Metrics
● Resource Consumption
○ Measuring resources (CPU, Memory, Disk) in correlation to other metrics like response time
or throughput.
● Efficiency
○ Performance divided by resources.
● Latency
○ Minimum time required to get any form of response, even if the work to be done is
nonexistent.
Performance is either
throughput or response time,
but in web application response
time is more popular.
Why should we care about web application
performance?
Performance is critical to success of any Web App.
Small performance fluctuations affects traffic and sales.
Poor performance of a web application can results in:
● Increasing bounce rate.
● Decreasing page views.
● Decreasing Conversion rate.
● Losing visitors and sales.
● Losing Ad revenue.
“A 1-second delay in page load time equals 11% fewer page views, a 16%
decrease in customer satisfaction, and 7% loss in conversions”
- Aberdeen Group
71% of users expects your
mobile site to load as quickly as
your desktop site
Some of best practices to optimize page load time
● Reduce HTTP requests
● Use a CDN (Content Delivery Network)
● Make pages cacheable
● Use gzip page compression
● Place stylesheets at the top
● Place scripts at the bottom
● Minify JavaScript and CSS
● Post/pre load components
● Maximize parallel downloads
● Optimize Images
● Use CSS sprites
… and many more
What is a responsive web application?
Although highly responsive application differ widely from one another,
they share the following characteristics:
● They give immediate feedback to the users.
● They handle queued requests as user would expect.
● They let users do other work while long operations proceed to completion.
● They provide enough feedback to users to understand what they are doing.
● They let users know when processing is in progress.
● They let users know or estimate how long lengthy operations will take.
● They let users stop requested tasks that have started but not finished.
Highly responsive applications put
users in control by quickly
acknowledging each user requests,
by providing continuous feedback
about progress towards fulfilling
each request, and by letting users
complete tasks without
unacceptable delays.
How to make web application responsive and have good user
experience?
● Keep framerate high and consistent
○ If the application running at 60 FPS, user is not going to notice any delay.
○ It means you have 16ms per frame to have a synchronous block of work done.
○ In Web, browser need 8ms to update DOM, so you are left with 8ms to get work done.
○ Keep main UI thread as free as possible.
○ Avoid DOM manipulations inside loops.
○ Don’t animate from JavaScript, Use requestAnimationFrame.
○ Promote GPU layers smartly.
● Provide immediate feedback.
○ Remember a response in 100ms is immediate feedback.
● Be careful with some design features
○ Transforms: translate, scale, rotate and opacity - GPU.
○ Border-radius, gradients, shadows, filters - CPU repaint.
General problem with web applications
JavaScript nature is...
● Async and single threaded.
● JavaScript code runs in the same thread as the UI.
● All JavaScript method calls, apart from ajax-related ones, are by default
synchronous.
● This is fine at first, but when JavaScript is doing any heavy-lifting, it can lock
up the browser. Locking up the browser is very bad.
● The browsers are blocked to avoid concurrency problems and if the blocks
lasts for more than a few seconds, browser present a warning message with
a choice to stop the long running scripts.
Things that can easily make browser unresponsive
● Parsing a large JSON data set.
● Image processing.
● Sound processing.
● Running prediction algorithm.
● Generating very large table.
● Real time analytics.
● Complex data visualizations.
Can’t we just do it on the Server?
It cost more to transmit a byte than to
compute it
Numbers we should know
Web workers to rescue
Web workers
● Commonly associated with HTML5.
● Lightweight in-browser threads that allow for asynchronous JavaScript
execution.
● JavaScript runs in separate thread isolated from the DOM.
● Does not delay UI updates as it does not block the main browser process.
● Communicate with main thread via message passing.
● JSON message based communication.
● No shared memory.
● Take advantage of multi-core processors.
Benefits of Web workers
● Application logic doesn’t block render thread.
● Better complete performance by using multi-core processor.
● Can run application across multiple windows or frames.
● Faster and more responsive.
● Enable better testing and can be tested without browser.
● Supported in all major browsers (IE10+).
Challenges with Web workers
● No Access to:
○ DOM
○ Window
○ Document
○ Parent
● No shared memory between web worker and main app.
● Serialization for message passing.
● Doesn’t work if the web page is being served from file. (file://url).
● Limited by same origin policy.
Browser support
Browser versions that fully support web workers:
A simple example
Create an html file(index.html) and add above code to show current time, echo a message typed in the
text box and buttons to start CPU intensive calculations in two different mode.
<!DOCTYPE html>
<html>
<title>Simple Web Worker</title>
<body>
<p>Current time is: <output id="currentTime"></output></p>
<label>Type message: </label><input type="text" onkeyup="showMessage(event);" value=""> Echo
message:<label id="message"></label>
<h3>CPU intensive processing in non web worker mode</h3>
<button onclick="startCalcInMainThread()">Process</button>
<h5>Total Iterations: <output id="resultMainThread"></output></h5>
<p>UI will be blocked during this calculation. The current time will stop updating and you won't be
able to enter message in text box. </p>
<br>
<h3>CPU intensive processing in web worker mode</h3>
<button onclick="startCalcInWorkerThread()">Process</button>
<h5>Total Iterations: <output id="resultWorkerThread"></output></h5>
<p>UI remains responsive during this calculation. The current time will keep updating and you will be
able to enter message in text box. </p>
</body>
</html>
Add an script tag in the body and below html tags added in previous slide. Add JavaScript code to show
current time and echo message typed in the text box.
<script>
window.setInterval(function() {
let now = new Date();
let h = now.getHours();
let m = now.getMinutes();
let s = now.getSeconds();
let ms = now.getMilliseconds();
document.getElementById("currentTime").innerHTML = h +':' + m + ':' + s + '.' + ms;
},100);
function showMessage(e) {
document.getElementById('message').innerHTML = e.currentTarget.value;
}
</script>
In the script tag, add JS code for handler functions to start CPU intensive processing in main thread
and web worker thread.
function startCalcInMainThread() {
document.getElementById("resultMainThread").innerHTML = CpuIntensiveCalc(10000);
}
function startCalcInWorkerThread() {
if(typeof(Worker) !== "undefined") {
let worker = new Worker("my-worker.js");
worker.onmessage = function(event) {
document.getElementById("resultWorkerThread").innerHTML = event.data;
}
worker.postMessage(10000);
} else {
document.getElementById("resultWorkerThread").innerHTML = "Web worker not supported!";
}
}
In script tag, add a function to perform CPU intensive processing for a given duration. The function
enters in a while loop and keep looping through it until the given time duration is over and returns the
number of iterations it has done in the loop.
function CpuIntensiveCalc(duration) {
const before = new Date();
let count = 0;
while (true) {
count++;
const now = new Date();
if (now.valueOf() - before.valueOf() > duration) {
break;
}
}
return count;
}
Create a javascript file(my-worker.js) and add above code to run CPU intensive processing in worker
thread. Please note that the function for processing logic is same as we had in html file with a minor
change. Here the function post message with iteration count value, instead of returning it.
addEventListener('message', (event) => {
CpuIntensiveCalc(event.data);
});
function CpuIntensiveCalc(duration) {
const before = new Date();
let count = 0;
while (true) {
count++;
const now = new Date();
if (now.valueOf() - before.valueOf() > duration) {
break;
}
}
postMessage(count);
}
Running the example
As we have created all the files mentioned in previous slides. Let’s run it now:
● Since web worker doesn’t work from file (file:url) so we need to host our files
in a web server. We can use NodeJS and http-server module to run this
application. Alternatively you can host these files in any web server.
○ Install http-server module globally using command “npm install http-server -g”
○ Open a command window from the directory containing the files and run command “http-
server -p 3001”, it will start the server listening on localhost:3001 and serve the files stored in
the directory.
○ Open browser and enter localhost:3001 in the url to access the application.
● You will notice the difference in application performance and responsiveness
in different modes of CPU intensive calculations.
● Complete code for this sample is available at: https://github.com/patidar-
suresh/simple-webworker
Web workers are great way to handle CPU intensive calculation of the
web applications.
Although web workers are simple to implement, we do see challenges
in integrating them with other frameworks like Angular with webpack.
I will be talking more on integrating web workers in an Angular
application created using angular-cli (without ejecting it).
Stay tuned and keep watching for more updates!
THANK YOU!

Contenu connexe

Tendances

How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...Katy Slemon
 
Reactjs Introduction - Virtual DOM
Reactjs Introduction - Virtual DOMReactjs Introduction - Virtual DOM
Reactjs Introduction - Virtual DOMTamir Azrab
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 dayQuach Long
 
AngularJS + React
AngularJS + ReactAngularJS + React
AngularJS + Reactjustvamp
 
How to optimize the performance of vue js large application structure
How to optimize the performance of vue js large application structure How to optimize the performance of vue js large application structure
How to optimize the performance of vue js large application structure Katy Slemon
 
Architecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web AppsArchitecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web AppsRasheed Waraich
 
Say Hello to React day2 presentation
Say Hello to React   day2 presentationSay Hello to React   day2 presentation
Say Hello to React day2 presentationSmile Gupta
 
Angular 1.x reloaded: improve your app now! and get ready for 2.0
Angular 1.x reloaded:  improve your app now! and get ready for 2.0Angular 1.x reloaded:  improve your app now! and get ready for 2.0
Angular 1.x reloaded: improve your app now! and get ready for 2.0Carlo Bonamico
 
Create Restful Web Application With Node.js Express Framework
Create Restful Web Application With Node.js Express FrameworkCreate Restful Web Application With Node.js Express Framework
Create Restful Web Application With Node.js Express FrameworkEdureka!
 
Angular 2 overview
Angular 2 overviewAngular 2 overview
Angular 2 overviewJesse Warden
 
Client Vs. Server Rendering
Client Vs. Server RenderingClient Vs. Server Rendering
Client Vs. Server RenderingDavid Amend
 
Muhammad azamuddin introduction-to-reactjs
Muhammad azamuddin   introduction-to-reactjsMuhammad azamuddin   introduction-to-reactjs
Muhammad azamuddin introduction-to-reactjsPHP Indonesia
 
From MEAN to the MERN Stack
From MEAN to the MERN StackFrom MEAN to the MERN Stack
From MEAN to the MERN StackTroy Miles
 
Web Performance & Latest in React
Web Performance & Latest in ReactWeb Performance & Latest in React
Web Performance & Latest in ReactTalentica Software
 
Service Worker 201 (en)
Service Worker 201 (en)Service Worker 201 (en)
Service Worker 201 (en)Chang W. Doh
 
Grokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with CouchbaseGrokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with CouchbaseOliver N
 
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?AngularJS vs React JS vs Node JS: Which is Best For Web Development ?
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?MarkupBox
 

Tendances (20)

How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
 
Reactjs Introduction - Virtual DOM
Reactjs Introduction - Virtual DOMReactjs Introduction - Virtual DOM
Reactjs Introduction - Virtual DOM
 
learn mvc project in 7 day
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 day
 
AngularJS + React
AngularJS + ReactAngularJS + React
AngularJS + React
 
How to optimize the performance of vue js large application structure
How to optimize the performance of vue js large application structure How to optimize the performance of vue js large application structure
How to optimize the performance of vue js large application structure
 
Architecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web AppsArchitecture & Workflow of Modern Web Apps
Architecture & Workflow of Modern Web Apps
 
Say Hello to React day2 presentation
Say Hello to React   day2 presentationSay Hello to React   day2 presentation
Say Hello to React day2 presentation
 
Angular 1.x reloaded: improve your app now! and get ready for 2.0
Angular 1.x reloaded:  improve your app now! and get ready for 2.0Angular 1.x reloaded:  improve your app now! and get ready for 2.0
Angular 1.x reloaded: improve your app now! and get ready for 2.0
 
Create Restful Web Application With Node.js Express Framework
Create Restful Web Application With Node.js Express FrameworkCreate Restful Web Application With Node.js Express Framework
Create Restful Web Application With Node.js Express Framework
 
Angular 2 overview
Angular 2 overviewAngular 2 overview
Angular 2 overview
 
Client Vs. Server Rendering
Client Vs. Server RenderingClient Vs. Server Rendering
Client Vs. Server Rendering
 
What angular 13 will bring to the table
What angular 13 will bring to the table What angular 13 will bring to the table
What angular 13 will bring to the table
 
Muhammad azamuddin introduction-to-reactjs
Muhammad azamuddin   introduction-to-reactjsMuhammad azamuddin   introduction-to-reactjs
Muhammad azamuddin introduction-to-reactjs
 
From MEAN to the MERN Stack
From MEAN to the MERN StackFrom MEAN to the MERN Stack
From MEAN to the MERN Stack
 
Web Performance & Latest in React
Web Performance & Latest in ReactWeb Performance & Latest in React
Web Performance & Latest in React
 
Mvc Training
Mvc TrainingMvc Training
Mvc Training
 
Service Worker 201 (en)
Service Worker 201 (en)Service Worker 201 (en)
Service Worker 201 (en)
 
Grokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with CouchbaseGrokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with Couchbase
 
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?AngularJS vs React JS vs Node JS: Which is Best For Web Development ?
AngularJS vs React JS vs Node JS: Which is Best For Web Development ?
 
Angularjs tutorial
Angularjs tutorialAngularjs tutorial
Angularjs tutorial
 

Similaire à Developing high performance and responsive web apps using web worker

JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendVlad Fedosov
 
How NOT to get lost in the current JavaScript landscape
How NOT to get lost in the current JavaScript landscapeHow NOT to get lost in the current JavaScript landscape
How NOT to get lost in the current JavaScript landscapeRadosław Scheibinger
 
PrairieDevCon 2014 - Web Doesn't Mean Slow
PrairieDevCon 2014 -  Web Doesn't Mean SlowPrairieDevCon 2014 -  Web Doesn't Mean Slow
PrairieDevCon 2014 - Web Doesn't Mean Slowdmethvin
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JSFestUA
 
Developing For The Web
Developing For The WebDeveloping For The Web
Developing For The Webaleemb
 
Seo for single page applications
Seo for single page applicationsSeo for single page applications
Seo for single page applicationsJustinGillespie12
 
AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)Alex Ross
 
PyGrunn2013 High Performance Web Applications with TurboGears
PyGrunn2013  High Performance Web Applications with TurboGearsPyGrunn2013  High Performance Web Applications with TurboGears
PyGrunn2013 High Performance Web Applications with TurboGearsAlessandro Molina
 
JavascriptMVC: Another choice of web framework
JavascriptMVC: Another choice of web frameworkJavascriptMVC: Another choice of web framework
JavascriptMVC: Another choice of web frameworkAlive Kuo
 
COMP6210 Web Services And Design Methodologies.docx
COMP6210 Web Services And Design Methodologies.docxCOMP6210 Web Services And Design Methodologies.docx
COMP6210 Web Services And Design Methodologies.docxwrite31
 
Client vs Server Templating: Speed up initial load for SPA with Angular as an...
Client vs Server Templating: Speed up initial load for SPA with Angular as an...Client vs Server Templating: Speed up initial load for SPA with Angular as an...
Client vs Server Templating: Speed up initial load for SPA with Angular as an...David Amend
 
An Introduction to Pagespeed Optimisation
An Introduction to Pagespeed OptimisationAn Introduction to Pagespeed Optimisation
An Introduction to Pagespeed OptimisationPratyush Majumdar
 
Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008codebits
 
Web performance optimization - MercadoLibre
Web performance optimization - MercadoLibreWeb performance optimization - MercadoLibre
Web performance optimization - MercadoLibrePablo Moretti
 
7 secrets of performance oriented front end development services
7 secrets of performance oriented front end development services7 secrets of performance oriented front end development services
7 secrets of performance oriented front end development servicesKaty Slemon
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performancekaven yan
 

Similaire à Developing high performance and responsive web apps using web worker (20)

JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontend
 
How NOT to get lost in the current JavaScript landscape
How NOT to get lost in the current JavaScript landscapeHow NOT to get lost in the current JavaScript landscape
How NOT to get lost in the current JavaScript landscape
 
PrairieDevCon 2014 - Web Doesn't Mean Slow
PrairieDevCon 2014 -  Web Doesn't Mean SlowPrairieDevCon 2014 -  Web Doesn't Mean Slow
PrairieDevCon 2014 - Web Doesn't Mean Slow
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
 
Dust.js
Dust.jsDust.js
Dust.js
 
Lighthouse
LighthouseLighthouse
Lighthouse
 
Developing For The Web
Developing For The WebDeveloping For The Web
Developing For The Web
 
Seo for single page applications
Seo for single page applicationsSeo for single page applications
Seo for single page applications
 
AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)
 
Modern Web Applications
Modern Web ApplicationsModern Web Applications
Modern Web Applications
 
PyGrunn2013 High Performance Web Applications with TurboGears
PyGrunn2013  High Performance Web Applications with TurboGearsPyGrunn2013  High Performance Web Applications with TurboGears
PyGrunn2013 High Performance Web Applications with TurboGears
 
JavascriptMVC: Another choice of web framework
JavascriptMVC: Another choice of web frameworkJavascriptMVC: Another choice of web framework
JavascriptMVC: Another choice of web framework
 
COMP6210 Web Services And Design Methodologies.docx
COMP6210 Web Services And Design Methodologies.docxCOMP6210 Web Services And Design Methodologies.docx
COMP6210 Web Services And Design Methodologies.docx
 
Client vs Server Templating: Speed up initial load for SPA with Angular as an...
Client vs Server Templating: Speed up initial load for SPA with Angular as an...Client vs Server Templating: Speed up initial load for SPA with Angular as an...
Client vs Server Templating: Speed up initial load for SPA with Angular as an...
 
Browser Based Performance Testing and Tuning
Browser Based Performance Testing and TuningBrowser Based Performance Testing and Tuning
Browser Based Performance Testing and Tuning
 
An Introduction to Pagespeed Optimisation
An Introduction to Pagespeed OptimisationAn Introduction to Pagespeed Optimisation
An Introduction to Pagespeed Optimisation
 
Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008Practical Thin Server Architecture With Dojo Sapo Codebits 2008
Practical Thin Server Architecture With Dojo Sapo Codebits 2008
 
Web performance optimization - MercadoLibre
Web performance optimization - MercadoLibreWeb performance optimization - MercadoLibre
Web performance optimization - MercadoLibre
 
7 secrets of performance oriented front end development services
7 secrets of performance oriented front end development services7 secrets of performance oriented front end development services
7 secrets of performance oriented front end development services
 
Ajax Performance
Ajax PerformanceAjax Performance
Ajax Performance
 

Plus de 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
 
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
 

Plus de Suresh Patidar (7)

Conducting Effective Interviews
Conducting Effective InterviewsConducting Effective Interviews
Conducting Effective Interviews
 
Conducting Good Interviews
Conducting Good InterviewsConducting Good Interviews
Conducting Good Interviews
 
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
 

Dernier

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.pdfWave PLM
 
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 🔝✔️✔️Delhi Call girls
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
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
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
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 ...OnePlan Solutions
 
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 studentsHimanshiGarg82
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
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...ICS
 
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 TechniquesVictorSzoltysek
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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...panagenda
 
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
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
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.pdfproinshot.com
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
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-learnAmarnathKambale
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Dernier (20)

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
 
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 🔝✔️✔️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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 ...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
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 ...
 
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
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
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...
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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...
 
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
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Developing high performance and responsive web apps using web worker

  • 1. Developing High Performance and Responsive Web Applications using Web Worker By:- Suresh Patidar 2nd September 2018
  • 2. Who am I? My name is Suresh Patidar and I’m from Pune, India. I work for Calsoft Inc. full-time as Senior Architect where I design architecture and solution for products in Storage, Networking, Virtualization, Cloud, IOT and ML domain. I’m primarily a UI/UX person and works extensively in web technologies and frameworks like HTML5/CSS3, JavaScript, TypeScript, Angular, React, Bootstrap, Backbone, NodeJS etc.
  • 3. Agenda ● What is web application performance? ● Why should we care about web application performance? ● Some of best practices to optimize page load time. ● What is a responsive web application? ● General problem with web applications. ● Web Workers to rescue. ● Benefits of Web Workers. ● Challenges with Web Workers. ● Browser support. ● A simple example.
  • 4. What is web application performance?
  • 5. “Web performance refers to the speed in which web pages are downloaded and displayed on the user’s browser” - From Wikipedia
  • 6. “The delay perceived by the web application user between an action(e.g. Click) and a meaningful response” - My definition
  • 7. Performance Metrics ● Response Time - ○ How long it takes to process a request ● Throughput ○ Number of requests that the application can process within defined time interval ● System Availability ○ Percentage of the application’s run time minus the time application can’t be accessed ● Responsiveness ○ How quickly the system acknowledge a request as opposed to processing it ● Request Rate ○ Metric to track the number of concurrent users.
  • 8. Performance Metrics ● Resource Consumption ○ Measuring resources (CPU, Memory, Disk) in correlation to other metrics like response time or throughput. ● Efficiency ○ Performance divided by resources. ● Latency ○ Minimum time required to get any form of response, even if the work to be done is nonexistent.
  • 9. Performance is either throughput or response time, but in web application response time is more popular.
  • 10. Why should we care about web application performance?
  • 11. Performance is critical to success of any Web App. Small performance fluctuations affects traffic and sales. Poor performance of a web application can results in: ● Increasing bounce rate. ● Decreasing page views. ● Decreasing Conversion rate. ● Losing visitors and sales. ● Losing Ad revenue. “A 1-second delay in page load time equals 11% fewer page views, a 16% decrease in customer satisfaction, and 7% loss in conversions” - Aberdeen Group
  • 12. 71% of users expects your mobile site to load as quickly as your desktop site
  • 13. Some of best practices to optimize page load time
  • 14. ● Reduce HTTP requests ● Use a CDN (Content Delivery Network) ● Make pages cacheable ● Use gzip page compression ● Place stylesheets at the top ● Place scripts at the bottom ● Minify JavaScript and CSS ● Post/pre load components ● Maximize parallel downloads ● Optimize Images ● Use CSS sprites … and many more
  • 15. What is a responsive web application?
  • 16. Although highly responsive application differ widely from one another, they share the following characteristics: ● They give immediate feedback to the users. ● They handle queued requests as user would expect. ● They let users do other work while long operations proceed to completion. ● They provide enough feedback to users to understand what they are doing. ● They let users know when processing is in progress. ● They let users know or estimate how long lengthy operations will take. ● They let users stop requested tasks that have started but not finished.
  • 17. Highly responsive applications put users in control by quickly acknowledging each user requests, by providing continuous feedback about progress towards fulfilling each request, and by letting users complete tasks without unacceptable delays.
  • 18. How to make web application responsive and have good user experience? ● Keep framerate high and consistent ○ If the application running at 60 FPS, user is not going to notice any delay. ○ It means you have 16ms per frame to have a synchronous block of work done. ○ In Web, browser need 8ms to update DOM, so you are left with 8ms to get work done. ○ Keep main UI thread as free as possible. ○ Avoid DOM manipulations inside loops. ○ Don’t animate from JavaScript, Use requestAnimationFrame. ○ Promote GPU layers smartly. ● Provide immediate feedback. ○ Remember a response in 100ms is immediate feedback. ● Be careful with some design features ○ Transforms: translate, scale, rotate and opacity - GPU. ○ Border-radius, gradients, shadows, filters - CPU repaint.
  • 19. General problem with web applications
  • 20.
  • 21. JavaScript nature is... ● Async and single threaded. ● JavaScript code runs in the same thread as the UI. ● All JavaScript method calls, apart from ajax-related ones, are by default synchronous. ● This is fine at first, but when JavaScript is doing any heavy-lifting, it can lock up the browser. Locking up the browser is very bad. ● The browsers are blocked to avoid concurrency problems and if the blocks lasts for more than a few seconds, browser present a warning message with a choice to stop the long running scripts.
  • 22. Things that can easily make browser unresponsive ● Parsing a large JSON data set. ● Image processing. ● Sound processing. ● Running prediction algorithm. ● Generating very large table. ● Real time analytics. ● Complex data visualizations.
  • 23. Can’t we just do it on the Server?
  • 24. It cost more to transmit a byte than to compute it
  • 26. Web workers to rescue
  • 27. Web workers ● Commonly associated with HTML5. ● Lightweight in-browser threads that allow for asynchronous JavaScript execution. ● JavaScript runs in separate thread isolated from the DOM. ● Does not delay UI updates as it does not block the main browser process. ● Communicate with main thread via message passing. ● JSON message based communication. ● No shared memory. ● Take advantage of multi-core processors.
  • 28. Benefits of Web workers ● Application logic doesn’t block render thread. ● Better complete performance by using multi-core processor. ● Can run application across multiple windows or frames. ● Faster and more responsive. ● Enable better testing and can be tested without browser. ● Supported in all major browsers (IE10+).
  • 29. Challenges with Web workers ● No Access to: ○ DOM ○ Window ○ Document ○ Parent ● No shared memory between web worker and main app. ● Serialization for message passing. ● Doesn’t work if the web page is being served from file. (file://url). ● Limited by same origin policy.
  • 30. Browser support Browser versions that fully support web workers:
  • 32. Create an html file(index.html) and add above code to show current time, echo a message typed in the text box and buttons to start CPU intensive calculations in two different mode. <!DOCTYPE html> <html> <title>Simple Web Worker</title> <body> <p>Current time is: <output id="currentTime"></output></p> <label>Type message: </label><input type="text" onkeyup="showMessage(event);" value=""> Echo message:<label id="message"></label> <h3>CPU intensive processing in non web worker mode</h3> <button onclick="startCalcInMainThread()">Process</button> <h5>Total Iterations: <output id="resultMainThread"></output></h5> <p>UI will be blocked during this calculation. The current time will stop updating and you won't be able to enter message in text box. </p> <br> <h3>CPU intensive processing in web worker mode</h3> <button onclick="startCalcInWorkerThread()">Process</button> <h5>Total Iterations: <output id="resultWorkerThread"></output></h5> <p>UI remains responsive during this calculation. The current time will keep updating and you will be able to enter message in text box. </p> </body> </html>
  • 33. Add an script tag in the body and below html tags added in previous slide. Add JavaScript code to show current time and echo message typed in the text box. <script> window.setInterval(function() { let now = new Date(); let h = now.getHours(); let m = now.getMinutes(); let s = now.getSeconds(); let ms = now.getMilliseconds(); document.getElementById("currentTime").innerHTML = h +':' + m + ':' + s + '.' + ms; },100); function showMessage(e) { document.getElementById('message').innerHTML = e.currentTarget.value; } </script>
  • 34. In the script tag, add JS code for handler functions to start CPU intensive processing in main thread and web worker thread. function startCalcInMainThread() { document.getElementById("resultMainThread").innerHTML = CpuIntensiveCalc(10000); } function startCalcInWorkerThread() { if(typeof(Worker) !== "undefined") { let worker = new Worker("my-worker.js"); worker.onmessage = function(event) { document.getElementById("resultWorkerThread").innerHTML = event.data; } worker.postMessage(10000); } else { document.getElementById("resultWorkerThread").innerHTML = "Web worker not supported!"; } }
  • 35. In script tag, add a function to perform CPU intensive processing for a given duration. The function enters in a while loop and keep looping through it until the given time duration is over and returns the number of iterations it has done in the loop. function CpuIntensiveCalc(duration) { const before = new Date(); let count = 0; while (true) { count++; const now = new Date(); if (now.valueOf() - before.valueOf() > duration) { break; } } return count; }
  • 36. Create a javascript file(my-worker.js) and add above code to run CPU intensive processing in worker thread. Please note that the function for processing logic is same as we had in html file with a minor change. Here the function post message with iteration count value, instead of returning it. addEventListener('message', (event) => { CpuIntensiveCalc(event.data); }); function CpuIntensiveCalc(duration) { const before = new Date(); let count = 0; while (true) { count++; const now = new Date(); if (now.valueOf() - before.valueOf() > duration) { break; } } postMessage(count); }
  • 37. Running the example As we have created all the files mentioned in previous slides. Let’s run it now: ● Since web worker doesn’t work from file (file:url) so we need to host our files in a web server. We can use NodeJS and http-server module to run this application. Alternatively you can host these files in any web server. ○ Install http-server module globally using command “npm install http-server -g” ○ Open a command window from the directory containing the files and run command “http- server -p 3001”, it will start the server listening on localhost:3001 and serve the files stored in the directory. ○ Open browser and enter localhost:3001 in the url to access the application. ● You will notice the difference in application performance and responsiveness in different modes of CPU intensive calculations. ● Complete code for this sample is available at: https://github.com/patidar- suresh/simple-webworker
  • 38. Web workers are great way to handle CPU intensive calculation of the web applications. Although web workers are simple to implement, we do see challenges in integrating them with other frameworks like Angular with webpack. I will be talking more on integrating web workers in an Angular application created using angular-cli (without ejecting it). Stay tuned and keep watching for more updates!