SlideShare a Scribd company logo
JavaScript Performance and
Best Practices

 Doris Chen Ph.D.
 Developer Evangelist
 doris.chen@microsoft.com
 http://blogs.msdn.com/b/dorischen/
 Twitter @doristchen
Who am I?
• Developer Evangelist at Microsoft based in Silicon Valley, CA
   – Blog: http://blogs.msdn.com/b/dorischen/
   – Twitter @doristchen
   – Email: doris.chen@microsoft.com
• 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)
Agenda
• Optimization Strategies


• JavaScript Best Practices
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
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
Manual Timing Method


function myFunctionToTest() {
var start = new Date().getTime();
... // body of the function
var totalTime = new Date().getTime() - start;
}
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.
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
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
Move scripts to the bottom (javascript)
>   Scripts block parallel downloads across all
    hostnames




>   Scripts block rendering of everything below them
    in the page
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
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
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">
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
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);
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;                                                                                                           Good
           ds.backgroundColor = "white";
}
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('');
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>";
    };
};
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
Example: Defer Loading Resources

<script>
var deferredLibs = [ '/resources/jquery.js' ,
'/resources/base.js'];
addLibraries(libs : deferredLibs,
             function(args) {
                // initialize components
              });
</script>
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);
  }
}
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
Use === Instead of ==

• two different kinds of equality operators: ===
  | !== and == | !=
• same type and value
  – === true
  – !== false
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!
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();
 }
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);
     }
Reduce Globals
    "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


        var name = doris';
        var lastName = chen';
        function doSomething() {...}
        console.log(name);
-----------------------------------------------------------------------------------------------------------------------------
        var DudeNameSpace = {
             name : 'Jeffrey',
             lastName : 'Way',
             doSomething : function() {...}
        }
        console.log(DudeNameSpace.name);
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
);

• Pass function name
 setInterval(someFunction, 3000);
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
Use [] Instead of New Array()

             var a = new Array();
             a[0] = "Joe";
             a[1] = 'Plumber';
----------------------------------------------------------------------------------------------------------------------

              var a = ['Joe','Plumber'];
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
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
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
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,...
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.
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
Resources
>   Best practices and Guidelines
       http://developer.yahoo.com/performance/rules.ht
        ml
>   Useful Sites
       http://stevesouders.com/
       http://javascript.crockford.com/
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
JavaScript Performance and
Best Practices

 Doris Chen Ph.D.
 Developer Evangelist
 doris.chen@microsoft.com
 http://blogs.msdn.com/b/dorischen/
 Twitter @doristchen

More Related Content

What's hot (20)

How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
Aaron Gustafson
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
Robert Nyman
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
Java script
Java scriptJava script
Java script
vishal choudhary
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
Enrique Juan de Dios
 
Javascript
JavascriptJavascript
Javascript
theacadian
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
jeresig
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
raja kvk
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
Visual Engineering
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
Addy Osmani
 
Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing
Ran Mizrahi
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
Aaron Gustafson
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
Robert Nyman
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
jeresig
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
Doeun KOCH
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
raja kvk
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
Nicholas Jansma
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
Visual Engineering
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
Addy Osmani
 
Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing
Ran Mizrahi
 

Viewers also liked (7)

Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
brinsknaps
 
Heap and stack space in java
Heap and stack space in javaHeap and stack space in java
Heap and stack space in java
Talha Ocakçı
 
Javascript1 pdf
Javascript1 pdfJavascript1 pdf
Javascript1 pdf
Fajar Baskoro
 
Studi kelayakan
Studi kelayakanStudi kelayakan
Studi kelayakan
Fajar Baskoro
 
Java script
Java scriptJava script
Java script
Fajar Baskoro
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Matt Raible
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
brinsknaps
 
Heap and stack space in java
Heap and stack space in javaHeap and stack space in java
Heap and stack space in java
Talha Ocakçı
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Matt Raible
 
Ad

Similar to Performance Optimization and JavaScript Best Practices (20)

Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
Doris Chen
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
Justin Cataldo
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english version
Sabino Labarile
 
Java script
Java scriptJava script
Java script
Soham Sengupta
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
Stoyan Stefanov
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
Salvatore Fazio
 
Get Ahead with HTML5 on Moible
Get Ahead with HTML5 on MoibleGet Ahead with HTML5 on Moible
Get Ahead with HTML5 on Moible
markuskobler
 
JavaScript front end performance optimizations
JavaScript front end performance optimizationsJavaScript front end performance optimizations
JavaScript front end performance optimizations
Chris Love
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula
Sorin Chiprian
 
Web performance essentials - Goodies
Web performance essentials - GoodiesWeb performance essentials - Goodies
Web performance essentials - Goodies
Jerry Emmanuel
 
TypeScript and SharePoint Framework
TypeScript and SharePoint FrameworkTypeScript and SharePoint Framework
TypeScript and SharePoint Framework
Bob German
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011
Timothy Fisher
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
Alive Kuo
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
Adam Lu
 
Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016
Doris Chen
 
Building Cloud-Native Applications with Microsoft Windows Azure
Building Cloud-Native Applications with Microsoft Windows AzureBuilding Cloud-Native Applications with Microsoft Windows Azure
Building Cloud-Native Applications with Microsoft Windows Azure
Bill Wilder
 
Java script Learn Easy
Java script Learn Easy Java script Learn Easy
Java script Learn Easy
prince Loffar
 
JavaScripts & jQuery
JavaScripts & jQueryJavaScripts & jQuery
JavaScripts & jQuery
Asanka Indrajith
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
Ajax Performance Tuning and Best Practices
Ajax Performance Tuning and Best PracticesAjax Performance Tuning and Best Practices
Ajax Performance Tuning and Best Practices
Doris Chen
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
Justin Cataldo
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english version
Sabino Labarile
 
Get Ahead with HTML5 on Moible
Get Ahead with HTML5 on MoibleGet Ahead with HTML5 on Moible
Get Ahead with HTML5 on Moible
markuskobler
 
JavaScript front end performance optimizations
JavaScript front end performance optimizationsJavaScript front end performance optimizations
JavaScript front end performance optimizations
Chris Love
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula
Sorin Chiprian
 
Web performance essentials - Goodies
Web performance essentials - GoodiesWeb performance essentials - Goodies
Web performance essentials - Goodies
Jerry Emmanuel
 
TypeScript and SharePoint Framework
TypeScript and SharePoint FrameworkTypeScript and SharePoint Framework
TypeScript and SharePoint Framework
Bob German
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011
Timothy Fisher
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
Alive Kuo
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
Adam Lu
 
Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016
Doris Chen
 
Building Cloud-Native Applications with Microsoft Windows Azure
Building Cloud-Native Applications with Microsoft Windows AzureBuilding Cloud-Native Applications with Microsoft Windows Azure
Building Cloud-Native Applications with Microsoft Windows Azure
Bill Wilder
 
Java script Learn Easy
Java script Learn Easy Java script Learn Easy
Java script Learn Easy
prince Loffar
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
Ad

More from Doris Chen (20)

Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work Everywhere
Doris Chen
 
Angular mobile angular_u
Angular mobile angular_uAngular mobile angular_u
Angular mobile angular_u
Doris Chen
 
Lastest Trends in Web Development
Lastest Trends in Web DevelopmentLastest Trends in Web Development
Lastest Trends in Web Development
Doris Chen
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
Doris Chen
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Doris Chen
 
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterPractical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Doris Chen
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Doris Chen
 
What Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsWhat Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS Apps
Doris Chen
 
Windows 8 Opportunity
Windows 8 OpportunityWindows 8 Opportunity
Windows 8 Opportunity
Doris Chen
 
Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluent
Doris Chen
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Doris Chen
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
Doris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Doris Chen
 
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Doris Chen
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
Doris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
Doris Chen
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5
Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
Doris Chen
 
HTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and DesktopHTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and Desktop
Doris Chen
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work Everywhere
Doris Chen
 
Angular mobile angular_u
Angular mobile angular_uAngular mobile angular_u
Angular mobile angular_u
Doris Chen
 
Lastest Trends in Web Development
Lastest Trends in Web DevelopmentLastest Trends in Web Development
Lastest Trends in Web Development
Doris Chen
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
Doris Chen
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Doris Chen
 
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterPractical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Doris Chen
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Doris Chen
 
What Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsWhat Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS Apps
Doris Chen
 
Windows 8 Opportunity
Windows 8 OpportunityWindows 8 Opportunity
Windows 8 Opportunity
Doris Chen
 
Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluent
Doris Chen
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Doris Chen
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
Doris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Doris Chen
 
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Doris Chen
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
Doris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
Doris Chen
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5
Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
Doris Chen
 
HTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and DesktopHTML 5 Development for Windows Phone and Desktop
HTML 5 Development for Windows Phone and Desktop
Doris Chen
 

Recently uploaded (20)

Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Introducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and ARIntroducing FME Realize: A New Era of Spatial Computing and AR
Introducing FME Realize: A New Era of Spatial Computing and AR
Safe Software
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 

Performance Optimization and JavaScript Best Practices

  • 1. JavaScript Performance and Best Practices Doris Chen Ph.D. Developer Evangelist [email protected] http://blogs.msdn.com/b/dorischen/ Twitter @doristchen
  • 2. 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)
  • 3. Agenda • Optimization Strategies • JavaScript Best Practices
  • 4. 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
  • 5. 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
  • 6. Manual Timing Method function myFunctionToTest() { var start = new Date().getTime(); ... // body of the function var totalTime = new Date().getTime() - start; }
  • 7. 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.
  • 8. 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
  • 9. 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
  • 10. Move scripts to the bottom (javascript) > Scripts block parallel downloads across all hostnames > Scripts block rendering of everything below them in the page
  • 11. 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
  • 12. 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
  • 13. 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">
  • 14. 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
  • 15. 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);
  • 16. 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; Good ds.backgroundColor = "white"; }
  • 17. 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('');
  • 18. 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>"; }; };
  • 19. 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
  • 20. Example: Defer Loading Resources <script> var deferredLibs = [ '/resources/jquery.js' , '/resources/base.js']; addLibraries(libs : deferredLibs, function(args) { // initialize components }); </script>
  • 21. 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); } }
  • 22. 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
  • 23. Use === Instead of == • two different kinds of equality operators: === | !== and == | != • same type and value – === true – !== false
  • 24. 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!
  • 25. 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(); }
  • 26. 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); }
  • 27. Reduce Globals "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 var name = doris'; var lastName = chen'; function doSomething() {...} console.log(name); ----------------------------------------------------------------------------------------------------------------------------- var DudeNameSpace = { name : 'Jeffrey', lastName : 'Way', doSomething : function() {...} } console.log(DudeNameSpace.name);
  • 28. 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 ); • Pass function name setInterval(someFunction, 3000);
  • 29. 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
  • 30. Use [] Instead of New Array() var a = new Array(); a[0] = "Joe"; a[1] = 'Plumber'; ---------------------------------------------------------------------------------------------------------------------- var a = ['Joe','Plumber'];
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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,...
  • 35. 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.
  • 36. 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
  • 37. Resources > Best practices and Guidelines  http://developer.yahoo.com/performance/rules.ht ml > Useful Sites  http://stevesouders.com/  http://javascript.crockford.com/
  • 38. 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
  • 39. JavaScript Performance and Best Practices Doris Chen Ph.D. Developer Evangelist [email protected] http://blogs.msdn.com/b/dorischen/ Twitter @doristchen