jquery best practices
DESCRIPTION
TRANSCRIPT
04/10/23HUGE / ParentsConnect / 1
HUGE45 Main Street, 2nd Floor NY NY 11201718.625.4843 www.hugeinc.com
jQuery Best Practices
Being Awesome with jQuery
October 13th, 2009
HUGE / New Browsers 2
Why be awesome
• Performance
• Better for the team
jQuery Best Practices
HUGE / New Browsers 3
Selector Optimization
• Avoid the universal selector• Avoid the implied
jQuery Best Practices
$(“.buttons > *”) //no no no, not good, costly$(“.buttons”).children()
$(“.gender :radio”) //implied$(“.gender input:radio”) //way better
HUGE / New Browsers 4
Selector Optimization
• 1.3.3 will be right to left (Sizzle) – most of the time• Better to be more specific on the right hand side when you can
jQuery Best Practices
// Finding Nemo$(“.data td.nemo”)
Better than
$(“div.data .nemo”)
Don’t over do it
$(“.data table.guests td.nemo”)
• Fastest when you can find by ID $(“#id”)
$(“#table-data .nemo”)
HUGE / New Browsers 5
The power of .find()
• $(“#id”).find(“div”) // rules all when you can use an ID• Faster than $(“#id div”) – even though improved in 1.3.3• Better than $(“div”, “#id”) – start avoiding context selection
Typical:$(“div”).each {
$(“p.awesome”, this).css( … );}
Better:$(“div”).each {
$(this).find(“p.awesome”).css( … );}
jQuery Best Practices
HUGE / New Browsers 6
The power of .find()
Semantically easier to read and is less work for jQuery:
[ jquery-1.3.2.js ]
jQuery Best Practices
// HANDLE: $(expr, [context])// (which is just equivalent to: $(content).find(expr)} else
return jQuery( context ).find( selector );
HUGE / New Browsers 7
.live()
• Use .live() from now on when assigning event handling
jQuery Best Practices
$(“a.extra”).live(“click” , function() {alert( this.attr(“title”) );
});
Better than
$(“a.extra”).click( function() {alert( this.attr(“title”) );
});
• Speeds up page load – one event handler bound vs. many
• 1.3.3 is suppose to ship once “submit”, “change”, and “focus/blur” work in .live()
HUGE / New Browsers 8
Variables
• Start using $ on variables that represent jQuery objects
• Cache selections
jQuery Best Practices
$(“#nav li”).live(“mouseover” , function() {var dropDownMessage = “I’m lonely!”;var $dropDown = $(this).find(“div.dropdown”);if ($dropDown.length === 0) {
alert( dropDownMessage );} else {
$dropDown.show();}
});
HUGE / New Browsers 9
Variables
• Variable declaration on “one line”!
jQuery Best Practices
var test1 = 1;var test2 = function() {
// stuff};var test3 = test2(test1);
var test1 = 1, test2 = function() {
// stuff }, test3 = test2(test1);
HUGE / New Browsers 10
Variables
• Contain your global variables in a… global variable
jQuery Best Practices
Var MYAPP = {};
MYAPP.creator = {“first-name” : “Joe”,“last-name” : “Shmo”
};
MYAPP.flight = {airline: “Oceanic”,number: 915,departure: {
IATA: “JFK”time: “2004-09-22 14:55”,city: “New York”
},...
};
HUGE / New Browsers 11
DOM Manipulation
• Inserting HTML fragments
jQuery Best Practices
for (var i=0; i<250; i++) {$("<li>something</li>").attr("id", "foo" + i).appendTo("ul");
}
Is faster (in 1.3.3) than
for (var i=0; i<250; i++) {$("ul").append("<li id='foo" + i + "'>something</li>");
}
HUGE / New Browsers 12
DOM Manipulation
• Insert HTML after construction is complete; 1 operation
jQuery Best Practices
var s = “”;for (var i=0; i<250; i++) {
s = s + “<li>”+i+”</li>”;}$(“ul”).append(s);
Better than
for (var i=0; i<250; i++) {$(“ul”).append(“<li>”+i+”</li>”);
}
HUGE / New Browsers 13
Minimize DOM Touches
• The DOM is slow… the more you jQuery each element, the slower
• On user style change:
jQuery Best Practices
// the more “a.crazy” the more processingjQuery(“a.crazy”).css(“color”, “#BADA55”);
// one consistent load timejQuery(‘<style type=“text/css”> a.crazy {color:#BADA55} </style>’)
.appendTo(‘head’);
HUGE / New Browsers 14
Don’t act on absent elements
• Can have costly overhead• Try to check first
jQuery Best Practices
jQuery.fn.doOnce = function(func) {this.length && func.apply(this);return this;
}
$(“li.cartitems”).doOnce( function(){// do something
});
jQuery.fn.somethingElse = function(opts) {if (!this.length) return this;// do something else
}
HUGE / New Browsers 15
Understanding jQuery enclosures
• Document ready
jQuery Best Practices
$(document).ready( function() {// your stuff here
});
• Self-enclosed namespace / “self-executing enclosures”(function ($) {
forThisModule = function() {// only available for this “module”
}})(jQuery);
• Document ready combined with self enclosurejQuery(function($) {
// your stuff here});
HUGE / New Browsers 16
Understanding jQuery enclosures
• Self-enclosed namespace / “self-executing enclosures”
jQuery Best Practices
• Assigns the dollar for jQuery usage and preserves it in that space
• Good to use if using another js library that has $ usage
(function ($) {forThisModule = function() {
// only available for this “module”}
})(jQuery);
HUGE / New Browsers 17
Understanding jQuery enclosures
• Document ready
jQuery Best Practices
$(document).ready( function() {// your stuff here
});
Is same as
jQuery(function($) {// your stuff here
});
• The latter better preserves the $, but not a big deal for us because we only use jQuery
• Should we use the latter as best practice?
HUGE / New Browsers 18
Listen to the Jehk
• Use object literals• Enclose your object literals
in an anonymous jQuery function
jQuery Best Practices