Posts Tagged ‘dom tree’

Some jQuery Mistakes

October 18, 2012 Leave a comment

Today I came across this article
I found couple of points very interesting, so just briefing few for reference:
1. You aren’t using the latest jQuery version :
Each version update means higher performance and several bug fixes. The current stable release is 1.7.2
2. You aren’t using a CDN-hosted copy of jQuery
For better performance use Google’s copy of jQuery instead of yours. If your user still has the cached file of Google’s website (or from many other sites that uses its CDN) his browser will just get the cached version, improving a lot your website’s performance. You can use it by copying & pasting this HTML:

3. You aren’t using a fallback :
Every time you rely upon external sources, make sure you have a local fallback.

window.jQuery || document.write('')

4. You aren’t chaining stuff
While doing common operations, you don’t need to call the element every time you want to manipulate it. If you’re doing several manipulations in a row, use chaining, so jQuery won’t need to get the element twice. e.g.
$(“#mydiv”).hide().css(“padding-left”, “50px”);
5. You aren’t caching stuff
This is one of the most important performance tips. If you’ll call an element at least twice, you should cache it. Caching is just saving the jQuery selector in a variable, so when you need to call it again you’ll just reference the variable and jQuery won’t need to search the whole DOM tree again to find your element.

/* you can use it this way because almost every jQuery function returns
the element, so $mydiv will be equal to $(“#mydiv”); also it’s good to
use the $mydiv so you know it’s a jQuery caching var */

var $mydiv = $(“#mydiv”).hide();
[.. lot of cool stuff going on here …]

6. You aren’t using pure js

Specially for attributes modification, we have several built in methods to get stuff done with pure javascript. You can even “convert” jQuery objects back to DOM nodes to use them with simpler methods, like this:

$mydiv[0].setAttribute('class', 'awesome'); //you can convert jQuery objects to DOM nodes using $jqObj[0]

Categories: General Tags: , ,