performance optimization and javascript best practices
DESCRIPTION
Performance optimization and JavaScript best practices tips are discussed in the talk. Here are some of the tips:Put stylesheets at the top (css)Move scripts to the bottom (javascript)Provide a clean separation of content, CSS, and JavaScriptDe-reference unused objectsThink AsynchronousWorking with ObjectsDefer Loading ResourcesUse JSLint -- Code Quality ToolReduce the size of JavaScript filegzipGeneral JavaScript Coding Best PracticesUse === Instead of ==Eval = BadDon’t Use Short-HandReduce Globals: NamespaceDon't Pass a String to "SetInterval" or "SetTimeOut" Use {} Instead of New Object()Use [] Instead of New Array()TRANSCRIPT
![Page 1: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/1.jpg)
JavaScript Performance and
Best Practices
Doris Chen Ph.D. Developer Evangelist
http://blogs.msdn.com/b/dorischen/ Twitter @doristchen
![Page 2: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/2.jpg)
Who am I?
• Developer Evangelist at Microsoft based in Silicon Valley, CA
– Blog: http://blogs.msdn.com/b/dorischen/
– Twitter @doristchen
– Email: [email protected]
• Has over 13 years of experience in the software industry focusing on
web technologies
• Spoke and published widely at JavaOne, O'Reilly, SD West, SD
Forum and worldwide User Groups meetings
• Before joining Microsoft, Doris Chen was a Technology Evangelist at
Sun Microsystems
• Doris received her Ph.D. from the University of California at Los
Angeles (UCLA)
![Page 3: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/3.jpg)
Agenda
• Optimization Strategies
• JavaScript Best Practices
![Page 4: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/4.jpg)
Ajaxify
• The client and server are in a dialog
• Make the messages between them as small as possible
• The client does not need a copy of the database
– just enough information to serve the user
• Don't rewrite the server application in JavaScript
![Page 5: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/5.jpg)
Don't Optimize Without Measuring
• Intuitions are often wrong
• A single trial is unreliable. Timers can be off by as much as 15 msec
• Even accurate measurements can lead to wrong conclusions
![Page 6: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/6.jpg)
Manual Timing Method
function myFunctionToTest() {
var start = new Date().getTime();
... // body of the function
var totalTime = new Date().getTime() - start;
}
![Page 7: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/7.jpg)
Only speed up things that take a lot of
time
• If profiling shows that you are spending most of your time in A, don't bother optimizing C.
![Page 8: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/8.jpg)
Don't Tune For Quirks
• Some browsers have surprising inefficiencies
• A trick that is faster on Browser A might be slower on Browser B
• The performance characteristics of the next generation may be significantly different
• Avoid short-term optimizations
![Page 9: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/9.jpg)
Put stylesheets at the top (css)
> Want the browser to display whatever content it has as soon as possible Avoids flash of unstyled content or blank white
screen > Solution: put stylesheets in document head
allows the page to render progressively > CSS at the bottom:
prohibits progressive rendering in many browsers, including Internet Explorer
browsers block rendering to avoid having to redraw elements of the page if their styles change
![Page 10: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/10.jpg)
Move scripts to the bottom (javascript)
> Scripts block parallel downloads across all hostnames
> Scripts block rendering of everything below them in the page
![Page 11: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/11.jpg)
JavaScript Best Practices
> Provide a clean separation of content, CSS, and JavaScript
> De-reference unused objects
> Think Asynchronous
> Working with Objects
> Defer Loading Resources
> General JavaScript Coding Best Practices
11
![Page 12: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/12.jpg)
Separation of content, CSS, and
JavaScript
> A rich web application user interface is made up of content (HTML/XHTML) styles (CSS) JavaScript
> Place CSS and JavaScript code in separate files Optimize the bandwidth usage by having CSS and
JavaScript file loaded only once
> Variables to decide using external or inline multiple page views per user per session many of pages re-use the same scripts and stylesheets
![Page 13: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/13.jpg)
Inline or External
• Inline JavaScript and CSS in front page, but dynamically download the external files after the page has finished loading
<style>#Styles</style>
<body>The quick brown fox...</body>
<script type="text/javascript">
// JavaScript logic
<script>
-------------------------------------------------------------------------------------
• For multiple views per user, and reusable scripts/css:
<link rel="stylesheet" type="text/css"
href="cart.css">
<body>The quick brown fox...</body>
<script type="text/javascript" src="cart.js">
![Page 14: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/14.jpg)
De-reference unused objects
//delete objects
var foo='Delete Me'; //do something with foo
delete foo;
// detach listeners
someElement.removeEventListener(type, fn, false);
// remove DOM elements
someElement.parentNode.removeChild(someElement);
// page onunload
window.onunload= function() { /*do something*/}
14
![Page 15: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/15.jpg)
Think Asynchronous > Prevents browsers from halting execution of a
code block that might take a long time
> Semi-Asynchronous – Like an Ajax request
Use a callback
> use setTimeout() in conjunction with a callback
function longProcess({ name : value}, callback) {
// do what needs to be done
callback.apply({});
}
setTimeout(function() {
longProcess({ name : “doris”}, function() {
alert(“all done”);
}
}, 0);
![Page 16: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/16.jpg)
Working with Objects (I)
var i;
for (i = 0; i < divs.length; i += 1) {
divs[i].style.color = "black";
divs[i].style.border = thickness + 'px solid blue';
divs[i].style.backgroundColor = "white";
}
-----------------------------------------------------------------------------------------------------------------------------------------------
var border = thickness + 'px solid blue';
var nrDivs = divs.length;
var ds, i;
for (i = 0; i < nrDivs; i += 1) {
ds = divs[i].style;
ds.color = "black";
ds.border = border;
ds.backgroundColor = "white";
}
Good
![Page 17: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/17.jpg)
Strings
• Concatenation with + – Each operation allocates memory
– foo = a + b;
• Concatenate with array.join('') – The contents of an array are concatenated into a
single string
– foo = [a, b].join('');
![Page 18: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/18.jpg)
Working with Objects (II) String Concatenation
window.tablebuilder = function() {
var _header, _rows = [];
this.setHeader = function(_headers) {
_header = "<tr><th>" + _headers.join("</th><th>") + "</tr>";
};
this.addRow = function(_cells) {
_rows.push("<tr><td>" + _cells.join("</td><td>") + "</td></tr>");
};
this.toString = function() {
return "<table>" + _header +
"<tbody>" + _rows.join("") + "</tbody>" +
"</table>";
};
};
![Page 19: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/19.jpg)
Defer Loading Resources
> If you have a large library or set of libraries, you don't need to load everything when a page is loaded
> Resources can be html, scripts, or css
Use Ajax Request
Add script/css links using DOM
![Page 20: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/20.jpg)
Example: Defer Loading Resources
<script>
var deferredLibs = [ '/resources/jquery.js' ,
'/resources/base.js'];
addLibraries(libs : deferredLibs,
function(args) {
// initialize components
});
</script>
![Page 21: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/21.jpg)
Example: Defer Loading Resources (cont.)
function addLibraries( libs, callback) {
for(var i=0; i < libs.length; i+=1) {
var head =
document.getElementsByTagName("head")[0];
var s = document.createElement("script");
// add callback tracking logic
s.src = libs[i];
head.appendChild(s);
}
}
![Page 22: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/22.jpg)
JavaScript Best Practices
> Provide a clean separation of content, CSS, and JavaScript
> De-reference unused objects
> Think Asynchronous
> Working with Objects
> Defer Loading Resources
> General JavaScript Coding Best Practices
22
![Page 23: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/23.jpg)
Use === Instead of ==
• two different kinds of equality operators: === | !== and == | !=
• same type and value
– === true
– !== false
![Page 24: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/24.jpg)
Eval = Bad
eval(string)
• eval function compiles and executes a string and returns the result
– gives us access to JavaScript’s compiler
• what the browser uses to convert strings into actions
• most misused feature of the language
– decreases script’s performance substantially
– also poses a huge security risk because it grants far too much power to the passed in text
• Avoid it if you can!
![Page 25: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/25.jpg)
Don’t Use Short-Hand
• Technically, get away with omitting most curly braces and semi-colons
if(someVariableExists) x = false anotherfunctionCall();
Interpreted by some browsers if(someVariableExists) { x = false;} anotherFunctionCall(); ----------------------------------------------------------------------------------------------------------------------------- -----
if(someVariableExists) { x = false; anotherFunctionCall(); }
-----------------------------------------------------------------------------------------------------------------------------
![Page 26: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/26.jpg)
Declare Variables Outside of the For
Statement
for(var i = 0; i < someArray.length; i++) { var container = document.getElementById('container'); container.innerHtml += 'my number: ' + i; console.log(i);
}
var container = document.getElementById('container'); for(var i = 0, len = someArray.length; i < len; i++) {
container.innerHtml += 'my number: ' + i; console.log(i);
}
----------------------------------------------------------------------------------------------------------------------
![Page 27: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/27.jpg)
Reduce Globals
var name = doris'; var lastName = chen'; function doSomething() {...} console.log(name);
var DudeNameSpace = { name : 'Jeffrey', lastName : 'Way', doSomething : function() {...}
} console.log(DudeNameSpace.name);
"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries." - Douglas Crockford
-----------------------------------------------------------------------------------------------------------------------------
![Page 28: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/28.jpg)
Don't Pass a String to "SetInterval"
or "SetTimeOut"
• Never pass a string to SetInterval and SetTimeOut
setInterval( "document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);
setInterval(someFunction, 3000);
• Pass function name
![Page 29: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/29.jpg)
Use {} Instead of New Object() var o = new Object(); o.name = 'Jeffrey'; o.lastName = 'Way'; o.someFunction = function() { console.log(this.name); }
var o = { name: 'Jeffrey', lastName = 'Way', someFunction : function() { console.log(this.name); }
};
var o = {}; //create empty object
----------------------------------------------------------------------------------------------------------------------
![Page 30: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/30.jpg)
Use [] Instead of New Array()
var a = new Array(); a[0] = "Joe"; a[1] = 'Plumber';
var a = ['Joe','Plumber'];
----------------------------------------------------------------------------------------------------------------------
![Page 31: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/31.jpg)
Code Quality
• High quality code is most likely to avoid platform problems.
• Code Conventions for the JavaScript Programming Language
– http://javascript.crockford.com/code.html
• Use JSLint.com. Pass with no warnings
![Page 32: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/32.jpg)
JSLint -- Code Quality Tool
• JSLint can help improve the robustness and portability of your programs – enforces style rules
– spot some errors that are very difficult to find in debugging
– It can help eliminate implied globals
• Integrated with tools, Visual Studio 2010 – http://jslint4vs2010.codeplex.com/
• Resources – http://www.jslint.com/
– http://www.javascriptlint.com/download.htm
![Page 33: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/33.jpg)
DOM Manipulation
• If JavaScript were infinitely fast, most pages would run at about the same speed.
• The bottleneck tends to be the DOM interface
• There is a significant cost every time you touch the DOM tree
• Each touch can result in a reflow computation, which is expensive
![Page 34: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/34.jpg)
Make good use of Ajax Libraries
• Effective code reuse will make widgets more effective
• JavaScript Toolkits
– Wrap up ajax details in javascript libraries
– jQuery, Dojo, prototype+scriptaculous, YUI,...
![Page 35: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/35.jpg)
Reduce the size of JavaScript file
• Reduce the amount of source code to reduce download time.
• Minification deletes whitespace and comments – While in development mode keep your scripts
readable so that they may be debugged easier
• Consider compressing your JavaScript resources when you deploy your application – If you use a 3rd party JavaScript library use the
compressed version if one is provided.
![Page 36: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/36.jpg)
Gzip components (server)
> you can affect users' download times Gzip supported in more browsers Gzip generally reduces the response size by 70%
> Not just for html, gzip all scripts, stylesheets, XML, JSON but not images, PDF Content-Encoding: gzip
> Gzip configuration HTTP request
Accept-Encoding: gzip, deflate
HTTP response Content-Encoding: gzip
![Page 37: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/37.jpg)
Resources
> Best practices and Guidelines http://developer.yahoo.com/performance/rules.ht
ml
> Useful Sites http://stevesouders.com/ http://javascript.crockford.com/
![Page 38: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/38.jpg)
Upcoming Web Camps
2 Days HTML5 and Web Development WebCamp
May 20-May 21st, 2011, Mountain View, CA
Free, learning innovative web technology, hands on experience
![Page 39: Performance Optimization and JavaScript Best Practices](https://reader033.vdocument.in/reader033/viewer/2022061218/54b6e1b24a7959215b8b4582/html5/thumbnails/39.jpg)
JavaScript Performance and
Best Practices
Doris Chen Ph.D. Developer Evangelist
http://blogs.msdn.com/b/dorischen/ Twitter @doristchen