A brief talk on web application performance and responsiveness. Why it is important and how web worker can help achieve it. It also covers a simple example implementing web workers.
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.
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.
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
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.
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.
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.
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!