1.Caching DOM Selectors
Every time you select a DOM element using jQuery, you are instantiating a new jQuery object and forcing jQuery to search the DOM.
Instead of creating multiple jQuery instances and forcing jQuery to re-query the DOM for a particular element, you can cache your jQuery object in a variable this will improve performance.
1
2
3
4
5
6
7
8
9
10
11
| // Stores the jQuery instance inside of a variablevar elem = jQuery("#elem");// Set's an element's title attribute using it's current textelem.attr("title", elem.text());// Set's an element's text color to redelem.css("color", "red");// Makes the element fade outelem.fadeOut(); |
1
2
3
4
5
| // Stores the live DOM element inside of a variablevar elem = jQuery("#elem");// Chainingelem.attr("title", elem.text()).css("color", "red").fadeOut(); |
2.Unobtrusive DOM Scripting
Never include Javascript events as inline attributes. This practice should be completely wiped from your mind.
Bad Code
1
| <a onclick="doSomething()" href="#">Click!</a> |
All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page. So, the anchor tag would appear like this:
Good Code
1
| <a href="#" class="doSomething">Click!</a> |
And the Javascript inside the myscript.js file would contain something like this:
1
2
3
4
| jQuery('a.doSomething').on("click",function( e ){ // Do something here! alert('You did something, woo hoo!');}); |
3.Avoid multiple jQuery(document).ready() calls
Executing code only after the DOM has been fully created, or the page content being fully loaded, is a good way of executing scripts. But it's unnecessary to repeat $(document).ready() or $(window).load() for each script you want to run. Better to just use it only once, and put your code inside a function.
1
2
3
4
5
6
7
8
9
10
| jQuery( document ).ready( function () { // all your code here});jQuery( window ).load( function () { // all your code here}); |
4.Selector Optimization
- Your jQuery selector is read from right to left.
- A class can belong to ANY element of your HTML page.
- An ID must be UNIQUE in your HTML page.
- The fastest way to find an element with Jquery is by ID, then by Tag element, then by Class.1
jQuery('.myClass').something();jQuery will have to check every element in your page before to return a result. You have two options to make this selector better: add a tag element, or add an ID before your class. If the tag element is a div, and you have plenty of div in your page, it will definitely help, but if you can get an id, pretty close to your class, you'll be in a better shape!1jQuery('#myID .myClass').something();//or $('ul.myClass').something();
5.jQuery Events
jQuery has seen a lot of different ways to bind an event to an element. The latest ones are .live(), .bind(), .delegate() and .on(). A lot of people have wondered which one to use and why. The answer is simple: .on()!!
Since jQuery 1.7 the methods .live(), .bind() and .delegate() are implicitly calling the on() method of your jQuery. The method .on() has multiple behaviors based on how you are declaring it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| /* The jQuery .bind(), .live(), and .delegate() methods are just one line pass throughs to the new jQuery 1.7 .on() method */ // BindjQuery( "#members li a" ).on( "click", function( e ) {} );jQuery( "#members li a" ).bind( "click", function( e ) {} ); // LivejQuery( document ).on( "click", "#members li a", function( e ) {} );jQuery( "#members li a" ).live( "click", function( e ) {} ); // DelegatejQuery( "#members" ).on( "click", "li a", function( e ) {} );jQuery( "#members" ).delegate( "li a", "click", function( e ) {} ); |
6. Use === to Test Equality
When testing equality, a lot of languages with syntax similar to JavaScript use the double equals operator (==). However, in JavaScript you should always use triple equals (===). The difference is in how equality is determined. A triple equals operator evaluates the two items based upon their type and value.
12345if(1 ==='1')//Returns falseif(1 =='1')//Returns trueif(0 ==='')//Returns falseif(0 =='')//Returns true
The first line would equal false because the number one does not equal the character 1. That is what we would expect. The double equals operator, on the other hand, will attempt to coerce the two values to be the same type before comparing equality. This can lead to unexpected results. In the second grouping, the result using the double equals would be true. That probably isn't what we were expecting.
7. Declare Variables Outside of the For Statement
When executing lengthy "for" statements, don't make the engine work any harder than it must. For example:
Bad Code
1
2
3
4
5
| for(var i = 0; i < someArray.length; i++) { var container = document.getElementById('container'); container.innerHtml += 'my number: ' + i; console.log(i);} |
Notice how we must determine the length of the array for each iteration, and how we traverse the dom to find the "container" element each time -- highly inefficient!
Good Code
1
2
3
4
5
| var container = document.getElementById('container');for(var i = 0, len = someArray.length; i < len; i++) { container.innerHtml += 'my number: ' + i; console.log(i);} |
8. Don't Pass a String to "SetInterval" or "SetTimeOut"
Consider the following code:
1
2
3
| setInterval("document.getElementById('container').innerHTML += 'My new number: ' + i", 3000); |
Not only is this code inefficient, but it also functions in the same way as the "eval" function would. Never pass a string to SetInterval and SetTimeOut. Instead, pass a function name.
1
| setInterval(someFunction, 3000); |
9. Use {} Instead of New Object()
There are multiple ways to create objects in JavaScript. Perhaps the more traditional method is to use the "new" constructor, like so:
Bad Code
1
2
3
4
5
6
| var o = new Object();o.name = 'Jeffrey';o.lastName = 'Way';o.someFunction = function() { console.log(this.name);} |
However, this method receives the "bad practice" stamp without actually being so. Instead, I recommend that you use the much more robust object literal method.
Good Code
1
2
3
4
5
6
7
| var o = { name: 'Jeffrey', lastName: 'Way', someFunction : function() { console.log(this.name); }}; |
10. Don't use try-catch-finally inside performance-critical functions
- The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.
- Exception handling should be done at as high level in the script where it does not occur frequently, for example outside a loop.
- Or if possible, avoid try-catch-finally completely
Bad Code
12345678varobject= ['foo','bar'], i;for(i = 0; i <object.length; i++) {try{// do something that throws an exception}catch(e) {// handle exception}}Good Code
12345678varobject= ['foo','bar'], i;try{for(i = 0; i <object.length; i++) {// do something}}catch(e) {// handle exception}

: