SlideShare a Scribd company logo
JavaScript Front-End
Performance Optimizations
Northeast JavaScript Conference
LOVE2DEV.COM
My Bio
Microsoft MVP
ASP Insider
Edge User Agent
Web Developer 25 years
Author & Speaker
@ChrisLove
Love2Dev.com
Source Code
http://GitHub.com/
docluv
Slide Deck
http://slideshare.net/docluv/
presentations
10 Days to HTML5 Fitness
http://bit.ly/2ctJMiU
JavaScript front end performance optimizations
Annoying???
LOVE2DEV.COM
"Also take a step back for a minute and consider the
intent of this change: a faster web is great for
everyone, but especially for users. Lots of websites have
demonstrated that speeding up the user experience
results in more usage. So speeding up your website isn’t
just something that can affect your search rankings–it’s a
fantastic idea for your users.“
http://bit.ly/SPPB4k
Matt Cutts
GOALS
Web Trends & Some History
Front-End Architecture Best Practices
Coding Syntax
Navigation & Performance Timing API
Build & Deploy
LOVE2DEV.COM
Web Trends & History
LOVE2DEV.COM
6 Years of JS Weight Gain
The Reach of JavaScript Expanded
Web Applications/SPAs
HTML5 Games
Basic Web Pages
JavaScript Execution Speed
DOM Interactions
Accelerated Graphics
Page Load Time
Conference Sponsor Sites Performance
LOVE2DEV.COM
Conference Sponsor Sites Averages
LOVE2DEV.COM
• Document Complete 6.94s
• Fully Loaded 8.7s
• Page Weight 2.8MB
• JS Weight 788kb
Web Sites Are Obese &
Out of Shape
http://httpArchive.org as of 5/15/2016
117 File Requests – 2.4+MB
23 JavaScript Files - 401KB
7.1 CSS Files – 74KB
56 Images – 1.577MB
36 TCP Connections
19 Domains
48% Cacheable
Is JavaScript the Problem?
JavaScript front end performance optimizations
YUI
Total
Size (k)
Number
Elements
CSS
Rules
Image
Files
Script
Lines (F)
Script
Libraries
Site #1 3,697 1,504 1,392 41 77,768
Site #2 2,278 1,100 5,325 29 39,183
Site #3 1,061 2,673 1,105 66 12,643
Site #4 1,812 4,252 1,672 12 10,284
Site #5 1,372 900 3,902 6 38,269
jQuery Prototype ExtJS OtherScriptaculous
YUI
Total
Size (k)
Number
Elements
CSS
Rules
Image
Files
Script
Lines (F)
Script
Libraries
Site #1 3,697 1,504 1,392 41 77,768
Site #2 2,278 1,100 5,325 29 39,183
Site #3 1,061 2,673 1,105 66 12,643
Site #4 1,812 4,252 1,672 12 10,284
Site #5 1,372 900 3,902 6 38,269
jQuery Prototype ExtJS OtherScriptaculous
Fastest
YUI
Total
Size (k)
Number
Elements
CSS
Rules
Image
Files
Script
Lines (F)
Script
Libraries
Site #1 3,697 1,504 1,392 41 77,768
Site #2 2,278 1,100 5,325 29 39,183
Site #3 1,061 2,673 1,105 66 12,643
Site #4 1,812 4,252 1,672 12 10,284
Site #5 1,372 900 3,902 6 38,269
jQuery Prototype ExtJS OtherScriptaculous
Slowest
Is JavaScript the Problem?
• Bytes Must Be Downloaded
• Bytes Cost Real Money
• 25% of US Exceeds Monthly Bandwidth
• Bytes Take Time
• Scripts Must Be Evaluated
• Libraries Can Overwrite Native APIs or Don’t Use Native
APIs
LOVE2DEV.COM
Don’t Guess
• Use Profiling Tools
• Establish Benchmarks
• < 1s Desktop/Broadband
• < 3s Mobile/GPRS
• Test On Real Devices Against ‘Real Site’
• Have a 2G Day
• Apply Scientific Method to Solve Problems
LOVE2DEV.COM
Establish a Performance Culture
• Make Perforamance a 1st Class Citizen of Your Team
• Include Developers, Architects, QA & Stakeholders
• Etsy Quarterly Performance Reports
• https://codeascraft.com/2016/04/28/q1-2016-site-
performance-report/
• Designing For Performance
• http://amzn.to/2d30GRy
Don’t Assume Broadband
What Does Your Site Cost?
http://whatdoesmysitecost.com
Power Consumption
Real & Perceived Performance
Architecture Best Practices
LOVE2DEV.COM
Place Script References At The Bottom
• SCRIPT is a Blocking Action
• Allow Browser to Render As Much As Possible Before
Evaluating & Executing Scripts
JS Parse & Execution Time
• Scripts Must Be Downloaded
• Scripts Must Be Evaluated
• Majority of Traffic from Mobile Class Devices
• Lower Powered CPU
• Less Memory
• Etsy Tool
• https://timkadlec.com/2014/09/js-parse-and-execution-time/
JavaScript front end performance optimizations
Best Practice
• Ask If Script/Library/Framework Is Really Needed
• Are Their Alternatives?
• Strive to Use Libraries Components That Do What
Needs to be Done
Best Practice – Libraries & Frameworks
• Use A Single Library
• Keep Library Up To Date
• Avoid Duplicate References
• Avoid Duplicate Versions
Avoid Duplicate Code
<html>
<head>
<title>Test</title>
</head>
<body>
…
<script src="jquery.js" … ></script>
<script src="myscript.js" … ></script>
<script src="navigation.js" … ></script>
<script src="jquery.js" … ></script>
</body>
</html>
Avoid Duplicate Code
52%of the pages on the web
have duplicate code
Standardize on Single Library/Framework
<script src="jquery.js" … ></script>
<script src="prototype.js" … ></script>
<script src="dojo.js" … ></script>
<script src="animater.js" … ></script>
<script src="extjs.js" … ></script>
<script src="yahooui.js" … ></script>
<script src="mochikit.js" … ></script>
<script src="lightbox.js" … ></script>
<script src="jslibs.js" … ></script>
<script src=“gsel.js" … ></script>
…
ASP.NET Web Client Library
Prototype
jQuery/jQueryUI
Ember
Angular
React
Ask If It Is Needed
• Avoid Framework Archeology
• Don’t Use a Library/Framework to be Cool
• Resume Driven Development
• Remember the Goal is to Make the Customer Happy
• They Pay the Bills!
• Majority of Pages/Sites are Still Read-Only
Use Async & Defer
• Allows Browser to Finish Rendering Cycle
• Use When Script Order is not important
• Use When Script is not needed to render
Audit 3rd Parties
3rd Parties
• Often Added By Marketing Departments
• Use of Tag Managers
• Many Are Not Used by Stakeholders
• Not Part of Application/Site Q/A
• Not Managed By DevOps
• Not Held to SLA
LOVE2DEV.COM
3rd Parties
• You Are Outsourcing Control Of Your Business To A
Supplier You Have Little or No Control
• They Can & Do Have A Big Impact On Your Brand Image
and Engagment
LOVE2DEV.COM
DOM Interactions
• Built In DOM Methods More Efficient
• Avoid Type Conversion
• Avoid DOM Chatiness
LOVE2DEV.COM
DOM Methods More Efficient
• querySelector
• querySelectorAll
• firstElementChild
• nextElementSibling
• previousElementSibling
• lastElementChild
• childElementCount
LOVE2DEV.COM
function InsertUsername()
{
document.getElementById('user').innerHTML = userName;
}
User .innerHTML to Construct Your Page
Use DOM Efficiently
function InsertUsername()
{
document.getElementById('user').innerHTML = userName;
}
User .innerHTML to Construct Your Page
Use DOM Efficiently
function BuildUI() {
var elm = document.getElementById('ui');
var contents = BuildTitle() + BuildBody() + BuildFooter();
elm.innerHTML = contents;
}
Batch Markup Changes
Use DOM Efficiently
function BuildUI() {
var elm = document.getElementById('ui');
var contents = BuildTitle() + BuildBody() + BuildFooter();
elm.innerHTML = contents;
}
Batch Markup Changes
Use DOM Efficiently
function BuildUI() {
var elm = document.getElementById('ui');
var contents = BuildTitle() + BuildBody() + BuildFooter();
elm.innerHTML = contents;
}
Batch Markup Changes
Use DOM Efficiently
function BuildUI() {
var elm = document.getElementById('ui');
var contents = BuildTitle() + BuildBody() + BuildFooter();
elm.innerHTML = contents;
}
Batch Markup Changes
Use DOM Efficiently
Small Healthy DOM
LOVE2DEV.COM
Use DOM Methods to Create Collections
LOVE2DEV.COM
Use DOM Selectors Collection Access
LOVE2DEV.COM
Avoid DOM Type Conversion
Avoid DOM Chatiness
Performance
• UI Responsiveness
• Identify CPU Intensive Code
• Identify Frame Rate Issues
• JavaScript Profiling
• Identify Code Bottlenecks
LOVE2DEV.COM
Memory Profiling
Memory Profiling
• Timeline to Identify Memory Pressure Issues
• Track Down Memory Leaks
LOVE2DEV.COM
Memory Utilization
Memory Leaks
Memory Leaks
Memory Leaks
Array Best Practices
• Pre-Allocate
• Keep Array Type Consistent
• Use Typed Arrays
• Keep Arrays Dense
• Enumerate Efficiently
LOVE2DEV.COM
Use Typed Arrays
LOVE2DEV.COM
Sparse vs Dense Arrays
• Arrays are Sparse, they have holes in them
• A map from indices to values
LOVE2DEV.COM
Sparse vs Dense Arrays
var a = new Array(3);
a [ , , ];
a.length === 3
a[0] === undefined
a.map(function (x, i) { return i }) === [ , , ]
LOVE2DEV.COM
Sparse vs Dense Arrays
• Array(undefined, undefined, undefined)
• a.map(function (x, i) { return i }) === [ 0, 1, 2 ]
LOVE2DEV.COM
Keep Arrays Dense
LOVE2DEV.COM
Enumerate Arrays Efficently
LOVE2DEV.COM
Don’t do useless work
setInterval(draw, 0);
setTimeout(draw, 0);
requestAnimationFrame(draw);
setTimeout(draw, 1000 / 60);
Do avoid chattiness with the DOM
JavaScript
DOM
for (var i = 0; i < this.nOfBubbles; i++) {
document.body.box.getElementById("ball0").style.left = b.x + "px";
document.body.box.getElementById("ball0").style.top = b.y + "px";
}
Do check types of values from DOM
this.nOfBubbles = document.getElementById(“dropDown").value;
30%
of rendering time in string conversion
Slow Operations
11%
Value Conversions
18%
GC 17%
Your Code 45%
JavaScript: Flexibility or performance
Flexibility Performance
“Think C++”“Think Script”
Simple Websites Complex Apps, Games
var r = 3 * "10"; // r == 300
var a = new Array();
a.push(10);
var p = {x: 0, y: 0};
p.z = 5;
p["some text"] = 1;
p[1] = 2;
eval("var s = p[1] * a[0]"); // s == 20
var r = 3 * parseInt("10");
var a = new Array(100);
a[0] = 10;
var p = new Point(0, 0, 0);
p.z = 5;
• C, C++, C# (Static Language)
• static int DoMath(int value) {
• int result = 0;
• for (int i = 0; i < 10000; i++) {
• for (int j = 0; j < 10000; j++)
{
• result = i + j + value;
• }
• }
• return result;
• }
JavaScript (Dynamic Language)
function DoMath(value) {
for (var i = 0; i < 10000; i++) {
for (var j = 0; j < 10000; j++) {
var result = i + j + value;
}
}
return result;
}
Stick to Integer Math
Write Fast JavaScript
Stick to Integer Math
Write Fast JavaScript
C++ JavaScript
DoMath(999);
40ms
200ms (~5x)
DoMath(999/2);
40ms
1600ms (~40x)
Stick to Integer Math
Write Fast JavaScript
0x005e22a0
Pointer
01
Type Tag
449.4999999……
…
Value
02
Type Tag
“Hello World”
Value
0x005e4148
Pointer
Stick to Integer Math
Write Fast JavaScript
DoMath(Math.floor(999 / 2));
var b = Math.ceil((p[i].r + p[i].g + p[i].b) / 3);
Stick to Integer Math
Write Fast JavaScript
DoMath(Math.floor(999 / 2));
var b = Math.ceil((p[i].r + p[i].g + p[i].b) / 3);
Stick to Integer Math
Write Fast JavaScript
DoMath(Math.floor(999 / 2));
var b = Math.ceil((p[i].r + p[i].g + p[i].b) / 3);
Do write fast objects
• Add all properties in constructor
• Don’t delete properties
• Use identifiers for property names
• Use getters and setters sparingly
• Avoid conditionally adding properties
• Avoid default property values on prototype objects
Navigation & Performance Timing APIs
• Give You Access to Real Times
• Various Stages of Document Lifecycle
• https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
• http://www.html5rocks.com/en/tutorials/webperformance/basics/
Navigation & Performance Timing APIs
How to Build JavaScript
• Maintain Development, QA, Production Versions
• Use a Build Tool
• Grunt, Gulp, WebPac, Broccoli, Node, etc
How to Build Production JavaScript
• Bundle & Minify
• A Single Request is much faster to download and parse
• Compress
• Gzip
• Content-Encoding Header
• Set Proper Cache Headers
• CacheControl: "public, max-age=31449600, s-max-age=360“
• Use A CDN
• Host on Static Server
How to Build Production JavaScript
• Node Modules Exists to Automate All these Requirements
• Set it and Forget It!

More Related Content

What's hot (20)

PPTX
Enough with the javas cript already! de Nicholas Zakas
Kubide
 
PDF
Building Progressive Web Apps for Android and iOS
FITC
 
KEY
Developing High Performance Web Apps - CodeMash 2011
Timothy Fisher
 
PPTX
HTML5 Web Workers-unleashed
Peter Lubbers
 
PDF
Thinking in Components
FITC
 
PDF
Extreme Web Performance for Mobile Devices - Velocity NY
Maximiliano Firtman
 
KEY
WHAT IS HTML5? (at CSS Nite Osaka)
Shumpei Shiraishi
 
KEY
Flash And Dom
Mike Wilcox
 
PDF
Client Vs. Server Rendering
David Amend
 
PPTX
Developing JavaScript Widgets
Bob German
 
PDF
Grokking #9: Building a real-time and offline editing service with Couchbase
Oliver N
 
PDF
Engineering the New LinkedIn Profile
Josh Clemm
 
PDF
Server and client rendering of single page apps
Thomas Heymann
 
PDF
The MEAN Stack
Md. Ziaul Haq
 
PDF
Progressive Web Apps
FITC
 
PDF
The fundamental problems of GUI applications and why people choose React
Oliver N
 
PDF
Build Better Responsive websites. Hrvoje Jurišić
MeetMagentoNY2014
 
PPTX
High-Speed HTML5
Peter Lubbers
 
KEY
An Introduction to webOS
Kevin Decker
 
PDF
Extending WordPress as a pro
Marko Heijnen
 
Enough with the javas cript already! de Nicholas Zakas
Kubide
 
Building Progressive Web Apps for Android and iOS
FITC
 
Developing High Performance Web Apps - CodeMash 2011
Timothy Fisher
 
HTML5 Web Workers-unleashed
Peter Lubbers
 
Thinking in Components
FITC
 
Extreme Web Performance for Mobile Devices - Velocity NY
Maximiliano Firtman
 
WHAT IS HTML5? (at CSS Nite Osaka)
Shumpei Shiraishi
 
Flash And Dom
Mike Wilcox
 
Client Vs. Server Rendering
David Amend
 
Developing JavaScript Widgets
Bob German
 
Grokking #9: Building a real-time and offline editing service with Couchbase
Oliver N
 
Engineering the New LinkedIn Profile
Josh Clemm
 
Server and client rendering of single page apps
Thomas Heymann
 
The MEAN Stack
Md. Ziaul Haq
 
Progressive Web Apps
FITC
 
The fundamental problems of GUI applications and why people choose React
Oliver N
 
Build Better Responsive websites. Hrvoje Jurišić
MeetMagentoNY2014
 
High-Speed HTML5
Peter Lubbers
 
An Introduction to webOS
Kevin Decker
 
Extending WordPress as a pro
Marko Heijnen
 

Similar to JavaScript front end performance optimizations (20)

PDF
Developing High Performance Web Apps
Timothy Fisher
 
PPTX
(Updated) SharePoint & jQuery Guide
Mark Rackley
 
PPTX
The SharePoint & jQuery Guide - Updated 1/14/14
Mark Rackley
 
PPT
Sanjeev ghai 12
Praveen kumar
 
PPTX
BrazilJS Perf Doctor Talk
Josh Holmes
 
PPTX
Hdv309 - Real World Sandboxed Solutions
woutervugt
 
PDF
Coding the UI
Mark Meeker
 
PDF
Coding Ui
rajivmordani
 
PPTX
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
PPTX
Introduction to Jquery
Gurpreet singh
 
PDF
Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5
Sadaaki HIRAI
 
PPTX
Javascript first-class citizenery
toddbr
 
PPTX
Internet protocol second unit IIPPT.pptx
ssuser92282c
 
PDF
Web Development for UX Designers
Ashlimarie
 
PDF
Top 45 jQuery Interview Questions and Answers | Edureka
Edureka!
 
PPTX
MongoDB.local Seattle 2019: MongoDB Stitch Tutorial
MongoDB
 
PPTX
Testing ASP.NET - Progressive.NET
Ben Hall
 
PDF
Web Performance Part 4 "Client-side performance"
Binary Studio
 
PPTX
HTML5.pptx
pramod jali
 
PDF
Ajax Performance Tuning and Best Practices
Doris Chen
 
Developing High Performance Web Apps
Timothy Fisher
 
(Updated) SharePoint & jQuery Guide
Mark Rackley
 
The SharePoint & jQuery Guide - Updated 1/14/14
Mark Rackley
 
Sanjeev ghai 12
Praveen kumar
 
BrazilJS Perf Doctor Talk
Josh Holmes
 
Hdv309 - Real World Sandboxed Solutions
woutervugt
 
Coding the UI
Mark Meeker
 
Coding Ui
rajivmordani
 
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
Introduction to Jquery
Gurpreet singh
 
Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5
Sadaaki HIRAI
 
Javascript first-class citizenery
toddbr
 
Internet protocol second unit IIPPT.pptx
ssuser92282c
 
Web Development for UX Designers
Ashlimarie
 
Top 45 jQuery Interview Questions and Answers | Edureka
Edureka!
 
MongoDB.local Seattle 2019: MongoDB Stitch Tutorial
MongoDB
 
Testing ASP.NET - Progressive.NET
Ben Hall
 
Web Performance Part 4 "Client-side performance"
Binary Studio
 
HTML5.pptx
pramod jali
 
Ajax Performance Tuning and Best Practices
Doris Chen
 
Ad

More from Chris Love (20)

PPTX
Quick Fetch API Introduction
Chris Love
 
PPTX
Introduction to Progressive Web Applications
Chris Love
 
PPTX
Introduction to Progressive Web Applications
Chris Love
 
PPTX
Lazy load Website Assets
Chris Love
 
PPTX
Progressive Web Apps for Education
Chris Love
 
PPTX
The server is dead going serverless to create a highly scalable application y...
Chris Love
 
PPTX
A Day Building Fast, Responsive, Extensible Single Page Applications
Chris Love
 
PPTX
Real World Lessons in Progressive Web Application & Service Worker Caching
Chris Love
 
PPTX
Using Responsive Web Design To Make Your Web Work Everywhere - Updated
Chris Love
 
PPTX
Implementing a Responsive Image Strategy
Chris Love
 
PPTX
Using Responsive Web Design To Make Your Web Work Everywhere
Chris Love
 
PPTX
10 things you can do to speed up your web app today 2016
Chris Love
 
PPT
Css best practices style guide and tips
Chris Love
 
PPTX
Using Responsive Web Design To Make Your Web Work Everywhere
Chris Love
 
PPTX
An Introduction to Microsoft Edge
Chris Love
 
PPTX
10 things you can do to speed up your web app today stir trek edition
Chris Love
 
PPTX
Single page applications the basics
Chris Love
 
PPTX
There Is No Mobile: An Introduction To Responsive Web Design
Chris Love
 
PPTX
Touch the web
Chris Love
 
PPTX
10 Things You Can Do to Speed Up Your Web App Today
Chris Love
 
Quick Fetch API Introduction
Chris Love
 
Introduction to Progressive Web Applications
Chris Love
 
Introduction to Progressive Web Applications
Chris Love
 
Lazy load Website Assets
Chris Love
 
Progressive Web Apps for Education
Chris Love
 
The server is dead going serverless to create a highly scalable application y...
Chris Love
 
A Day Building Fast, Responsive, Extensible Single Page Applications
Chris Love
 
Real World Lessons in Progressive Web Application & Service Worker Caching
Chris Love
 
Using Responsive Web Design To Make Your Web Work Everywhere - Updated
Chris Love
 
Implementing a Responsive Image Strategy
Chris Love
 
Using Responsive Web Design To Make Your Web Work Everywhere
Chris Love
 
10 things you can do to speed up your web app today 2016
Chris Love
 
Css best practices style guide and tips
Chris Love
 
Using Responsive Web Design To Make Your Web Work Everywhere
Chris Love
 
An Introduction to Microsoft Edge
Chris Love
 
10 things you can do to speed up your web app today stir trek edition
Chris Love
 
Single page applications the basics
Chris Love
 
There Is No Mobile: An Introduction To Responsive Web Design
Chris Love
 
Touch the web
Chris Love
 
10 Things You Can Do to Speed Up Your Web App Today
Chris Love
 
Ad

Recently uploaded (20)

PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PPTX
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
PPTX
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
PPT
Computer Securityyyyyyyy - Chapter 1.ppt
SolomonSB
 
PPTX
ZARA-Case.pptx djdkkdjnddkdoodkdxjidjdnhdjjdjx
RonnelPineda2
 
PPTX
internet básico presentacion es una red global
70965857
 
PPT
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PPTX
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
PDF
DevOps Design for different deployment options
henrymails
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PDF
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PPTX
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
PDF
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
PPTX
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
PPTX
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
Computer Securityyyyyyyy - Chapter 1.ppt
SolomonSB
 
ZARA-Case.pptx djdkkdjnddkdoodkdxjidjdnhdjjdjx
RonnelPineda2
 
internet básico presentacion es una red global
70965857
 
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
DevOps Design for different deployment options
henrymails
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
Orchestrating things in Angular application
Peter Abraham
 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 

JavaScript front end performance optimizations

  • 1. JavaScript Front-End Performance Optimizations Northeast JavaScript Conference LOVE2DEV.COM
  • 2. My Bio Microsoft MVP ASP Insider Edge User Agent Web Developer 25 years Author & Speaker @ChrisLove Love2Dev.com
  • 4. 10 Days to HTML5 Fitness http://bit.ly/2ctJMiU
  • 7. LOVE2DEV.COM "Also take a step back for a minute and consider the intent of this change: a faster web is great for everyone, but especially for users. Lots of websites have demonstrated that speeding up the user experience results in more usage. So speeding up your website isn’t just something that can affect your search rankings–it’s a fantastic idea for your users.“ http://bit.ly/SPPB4k Matt Cutts
  • 8. GOALS Web Trends & Some History Front-End Architecture Best Practices Coding Syntax Navigation & Performance Timing API Build & Deploy LOVE2DEV.COM
  • 9. Web Trends & History LOVE2DEV.COM
  • 10. 6 Years of JS Weight Gain
  • 11. The Reach of JavaScript Expanded Web Applications/SPAs HTML5 Games Basic Web Pages JavaScript Execution Speed DOM Interactions Accelerated Graphics Page Load Time
  • 12. Conference Sponsor Sites Performance LOVE2DEV.COM
  • 13. Conference Sponsor Sites Averages LOVE2DEV.COM • Document Complete 6.94s • Fully Loaded 8.7s • Page Weight 2.8MB • JS Weight 788kb
  • 14. Web Sites Are Obese & Out of Shape http://httpArchive.org as of 5/15/2016 117 File Requests – 2.4+MB 23 JavaScript Files - 401KB 7.1 CSS Files – 74KB 56 Images – 1.577MB 36 TCP Connections 19 Domains 48% Cacheable
  • 15. Is JavaScript the Problem?
  • 17. YUI Total Size (k) Number Elements CSS Rules Image Files Script Lines (F) Script Libraries Site #1 3,697 1,504 1,392 41 77,768 Site #2 2,278 1,100 5,325 29 39,183 Site #3 1,061 2,673 1,105 66 12,643 Site #4 1,812 4,252 1,672 12 10,284 Site #5 1,372 900 3,902 6 38,269 jQuery Prototype ExtJS OtherScriptaculous
  • 18. YUI Total Size (k) Number Elements CSS Rules Image Files Script Lines (F) Script Libraries Site #1 3,697 1,504 1,392 41 77,768 Site #2 2,278 1,100 5,325 29 39,183 Site #3 1,061 2,673 1,105 66 12,643 Site #4 1,812 4,252 1,672 12 10,284 Site #5 1,372 900 3,902 6 38,269 jQuery Prototype ExtJS OtherScriptaculous Fastest
  • 19. YUI Total Size (k) Number Elements CSS Rules Image Files Script Lines (F) Script Libraries Site #1 3,697 1,504 1,392 41 77,768 Site #2 2,278 1,100 5,325 29 39,183 Site #3 1,061 2,673 1,105 66 12,643 Site #4 1,812 4,252 1,672 12 10,284 Site #5 1,372 900 3,902 6 38,269 jQuery Prototype ExtJS OtherScriptaculous Slowest
  • 20. Is JavaScript the Problem? • Bytes Must Be Downloaded • Bytes Cost Real Money • 25% of US Exceeds Monthly Bandwidth • Bytes Take Time • Scripts Must Be Evaluated • Libraries Can Overwrite Native APIs or Don’t Use Native APIs LOVE2DEV.COM
  • 21. Don’t Guess • Use Profiling Tools • Establish Benchmarks • < 1s Desktop/Broadband • < 3s Mobile/GPRS • Test On Real Devices Against ‘Real Site’ • Have a 2G Day • Apply Scientific Method to Solve Problems LOVE2DEV.COM
  • 22. Establish a Performance Culture • Make Perforamance a 1st Class Citizen of Your Team • Include Developers, Architects, QA & Stakeholders • Etsy Quarterly Performance Reports • https://codeascraft.com/2016/04/28/q1-2016-site- performance-report/ • Designing For Performance • http://amzn.to/2d30GRy
  • 24. What Does Your Site Cost? http://whatdoesmysitecost.com
  • 26. Real & Perceived Performance
  • 28. Place Script References At The Bottom • SCRIPT is a Blocking Action • Allow Browser to Render As Much As Possible Before Evaluating & Executing Scripts
  • 29. JS Parse & Execution Time • Scripts Must Be Downloaded • Scripts Must Be Evaluated • Majority of Traffic from Mobile Class Devices • Lower Powered CPU • Less Memory • Etsy Tool • https://timkadlec.com/2014/09/js-parse-and-execution-time/
  • 31. Best Practice • Ask If Script/Library/Framework Is Really Needed • Are Their Alternatives? • Strive to Use Libraries Components That Do What Needs to be Done
  • 32. Best Practice – Libraries & Frameworks • Use A Single Library • Keep Library Up To Date • Avoid Duplicate References • Avoid Duplicate Versions
  • 33. Avoid Duplicate Code <html> <head> <title>Test</title> </head> <body> … <script src="jquery.js" … ></script> <script src="myscript.js" … ></script> <script src="navigation.js" … ></script> <script src="jquery.js" … ></script> </body> </html>
  • 34. Avoid Duplicate Code 52%of the pages on the web have duplicate code
  • 35. Standardize on Single Library/Framework <script src="jquery.js" … ></script> <script src="prototype.js" … ></script> <script src="dojo.js" … ></script> <script src="animater.js" … ></script> <script src="extjs.js" … ></script> <script src="yahooui.js" … ></script> <script src="mochikit.js" … ></script> <script src="lightbox.js" … ></script> <script src="jslibs.js" … ></script> <script src=“gsel.js" … ></script> …
  • 36. ASP.NET Web Client Library Prototype jQuery/jQueryUI Ember Angular React
  • 37. Ask If It Is Needed • Avoid Framework Archeology • Don’t Use a Library/Framework to be Cool • Resume Driven Development • Remember the Goal is to Make the Customer Happy • They Pay the Bills! • Majority of Pages/Sites are Still Read-Only
  • 38. Use Async & Defer • Allows Browser to Finish Rendering Cycle • Use When Script Order is not important • Use When Script is not needed to render
  • 40. 3rd Parties • Often Added By Marketing Departments • Use of Tag Managers • Many Are Not Used by Stakeholders • Not Part of Application/Site Q/A • Not Managed By DevOps • Not Held to SLA LOVE2DEV.COM
  • 41. 3rd Parties • You Are Outsourcing Control Of Your Business To A Supplier You Have Little or No Control • They Can & Do Have A Big Impact On Your Brand Image and Engagment LOVE2DEV.COM
  • 42. DOM Interactions • Built In DOM Methods More Efficient • Avoid Type Conversion • Avoid DOM Chatiness LOVE2DEV.COM
  • 43. DOM Methods More Efficient • querySelector • querySelectorAll • firstElementChild • nextElementSibling • previousElementSibling • lastElementChild • childElementCount LOVE2DEV.COM
  • 44. function InsertUsername() { document.getElementById('user').innerHTML = userName; } User .innerHTML to Construct Your Page Use DOM Efficiently
  • 45. function InsertUsername() { document.getElementById('user').innerHTML = userName; } User .innerHTML to Construct Your Page Use DOM Efficiently
  • 46. function BuildUI() { var elm = document.getElementById('ui'); var contents = BuildTitle() + BuildBody() + BuildFooter(); elm.innerHTML = contents; } Batch Markup Changes Use DOM Efficiently
  • 47. function BuildUI() { var elm = document.getElementById('ui'); var contents = BuildTitle() + BuildBody() + BuildFooter(); elm.innerHTML = contents; } Batch Markup Changes Use DOM Efficiently
  • 48. function BuildUI() { var elm = document.getElementById('ui'); var contents = BuildTitle() + BuildBody() + BuildFooter(); elm.innerHTML = contents; } Batch Markup Changes Use DOM Efficiently
  • 49. function BuildUI() { var elm = document.getElementById('ui'); var contents = BuildTitle() + BuildBody() + BuildFooter(); elm.innerHTML = contents; } Batch Markup Changes Use DOM Efficiently
  • 51. Use DOM Methods to Create Collections LOVE2DEV.COM
  • 52. Use DOM Selectors Collection Access LOVE2DEV.COM
  • 53. Avoid DOM Type Conversion
  • 55. Performance • UI Responsiveness • Identify CPU Intensive Code • Identify Frame Rate Issues • JavaScript Profiling • Identify Code Bottlenecks LOVE2DEV.COM
  • 57. Memory Profiling • Timeline to Identify Memory Pressure Issues • Track Down Memory Leaks LOVE2DEV.COM
  • 62. Array Best Practices • Pre-Allocate • Keep Array Type Consistent • Use Typed Arrays • Keep Arrays Dense • Enumerate Efficiently LOVE2DEV.COM
  • 64. Sparse vs Dense Arrays • Arrays are Sparse, they have holes in them • A map from indices to values LOVE2DEV.COM
  • 65. Sparse vs Dense Arrays var a = new Array(3); a [ , , ]; a.length === 3 a[0] === undefined a.map(function (x, i) { return i }) === [ , , ] LOVE2DEV.COM
  • 66. Sparse vs Dense Arrays • Array(undefined, undefined, undefined) • a.map(function (x, i) { return i }) === [ 0, 1, 2 ] LOVE2DEV.COM
  • 69. Don’t do useless work setInterval(draw, 0); setTimeout(draw, 0); requestAnimationFrame(draw); setTimeout(draw, 1000 / 60);
  • 70. Do avoid chattiness with the DOM JavaScript DOM for (var i = 0; i < this.nOfBubbles; i++) { document.body.box.getElementById("ball0").style.left = b.x + "px"; document.body.box.getElementById("ball0").style.top = b.y + "px"; }
  • 71. Do check types of values from DOM this.nOfBubbles = document.getElementById(“dropDown").value; 30% of rendering time in string conversion Slow Operations 11% Value Conversions 18% GC 17% Your Code 45%
  • 72. JavaScript: Flexibility or performance Flexibility Performance “Think C++”“Think Script” Simple Websites Complex Apps, Games var r = 3 * "10"; // r == 300 var a = new Array(); a.push(10); var p = {x: 0, y: 0}; p.z = 5; p["some text"] = 1; p[1] = 2; eval("var s = p[1] * a[0]"); // s == 20 var r = 3 * parseInt("10"); var a = new Array(100); a[0] = 10; var p = new Point(0, 0, 0); p.z = 5;
  • 73. • C, C++, C# (Static Language) • static int DoMath(int value) { • int result = 0; • for (int i = 0; i < 10000; i++) { • for (int j = 0; j < 10000; j++) { • result = i + j + value; • } • } • return result; • } JavaScript (Dynamic Language) function DoMath(value) { for (var i = 0; i < 10000; i++) { for (var j = 0; j < 10000; j++) { var result = i + j + value; } } return result; } Stick to Integer Math Write Fast JavaScript
  • 74. Stick to Integer Math Write Fast JavaScript C++ JavaScript DoMath(999); 40ms 200ms (~5x) DoMath(999/2); 40ms 1600ms (~40x)
  • 75. Stick to Integer Math Write Fast JavaScript 0x005e22a0 Pointer 01 Type Tag 449.4999999…… … Value 02 Type Tag “Hello World” Value 0x005e4148 Pointer
  • 76. Stick to Integer Math Write Fast JavaScript DoMath(Math.floor(999 / 2)); var b = Math.ceil((p[i].r + p[i].g + p[i].b) / 3);
  • 77. Stick to Integer Math Write Fast JavaScript DoMath(Math.floor(999 / 2)); var b = Math.ceil((p[i].r + p[i].g + p[i].b) / 3);
  • 78. Stick to Integer Math Write Fast JavaScript DoMath(Math.floor(999 / 2)); var b = Math.ceil((p[i].r + p[i].g + p[i].b) / 3);
  • 79. Do write fast objects • Add all properties in constructor • Don’t delete properties • Use identifiers for property names • Use getters and setters sparingly • Avoid conditionally adding properties • Avoid default property values on prototype objects
  • 80. Navigation & Performance Timing APIs • Give You Access to Real Times • Various Stages of Document Lifecycle • https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API • http://www.html5rocks.com/en/tutorials/webperformance/basics/
  • 82. How to Build JavaScript • Maintain Development, QA, Production Versions • Use a Build Tool • Grunt, Gulp, WebPac, Broccoli, Node, etc
  • 83. How to Build Production JavaScript • Bundle & Minify • A Single Request is much faster to download and parse • Compress • Gzip • Content-Encoding Header • Set Proper Cache Headers • CacheControl: "public, max-age=31449600, s-max-age=360“ • Use A CDN • Host on Static Server
  • 84. How to Build Production JavaScript • Node Modules Exists to Automate All these Requirements • Set it and Forget It!

Editor's Notes

  • #15: Update these #s before the presentation as they are always updating