jQuery Tips and Tricks II

Written by Kevin Liew on 07 Apr 2009
117,082 Views • Techniques

 

This is my second posts about jQuery Tips and Tricks. If you missed my first post, you might want to read it now useful and handy jQuery Tips and Tricks. This time, I found some performance tuning, element manipulations tips and tricks that I believe will able to help you develop a more effective and efficient jQuery script. Enjoy!

1. No conflict-mode

To avoid conflict when you are using multiple libraries in a website, you can use this jQuery Method, and assign a different variable name instead of the dollar sign. Using jQuery with other libraries

var $j = jQuery.noConflict();
$j('#myDiv').hide();

2. Total of selected elements

It return the number of elements that are selected by jQuery selector. Using length method will return the size of array which is equal to the number of selected objects.

$('.someClass').length;

3. Let Google host jQuery for you

There are advantages to let Google host jQuery. Some of us may not know, it actually provides better caching, increase parallelism and decreased latency compared with hosting it locally. Find out more about it: 3 reasons why you should let google host jQuery for you

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
    //Code to be inserted in this area
});
</script>

/* the best way (fastest and most efficient implementation) */
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    //This is more like it!
  });
</script>

4. Check if checkbox is checked

jQuery provides us 3 ways to determine if a checkbox is checked. How to check if checkbox is checked

// First way 
$('#checkBox').attr('checked'); 

// Second way 
$('#edit-checkbox-id').is(':checked'); 

// Third way 
$("[:checkbox]:checked").each(
    function() { 
       // Insert code here 
    } 
);

5. How to disabled/enable an element with jQuery

 

// To disable 
$('.someElement').attr('disabled', 'disabled'); 

// To enable 
$('.someElement').removeAttr('disabled'); 
// OR you can set attr to "" 
$('.someElement').attr('disabled', '');

6. Improving jQuery code performance

Selecting an element using ID is faster than selecting classname. jQuery Performance Analysis of selectors.

update: apparently, jQuery 1.3 has a big improvement on this. So, I guess this tips only suitable for old browsers and jQuery 1.2 or below. Thanks Karl for the information.

/* ID */
$("#myid").html();

/* is faster than class*/
$(".myclass").html();

If you use a classname, the jQuery will perform better if you attached the element to the class name. A good practise when selecting a class:

$("ul.myclass");

/* is faster than this*/

$(".myclass");

7. Javascript Error Checker

Debugging javascript script can be extremely time consuming. So, if you running out of ideas what is causing the errors, you can use this free online tool JSLint

8. Disable jQuery animations

This will disable all jQuery animations if it's set to true.

jQuery.fx.off = true;

9. IE Rendering problem in fadeIn effect

If you used the fadeIn effect in ie6 before, you probably able to notice how urgly it looks. The text doesn't render the way it should. To solve this, you need to remove the filter attribute

// This causes this text glich
$("#message").fadeIn();

// This will fix it
$("#message").removeAttr("filter");

10. Check if jQuery.js is loaded

 

/* Method 1 */
if (jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

/* Method 2 */
if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded  
} else {
    // jQuery is loaded
}

11. Add an icon for external links

This trick is pretty simple and good for usability. If links are linking to external website, an image will be displayed next to the link. Dynamically add an icon for external links

$(document).ready(function() {
  $('#extlinks a').filter(function() {
 return this.hostname && this.hostname !== location.hostname;
  }).after(' 
external link
');
});

MORE TIPS AND TRICKS ARE WANTED!

I hope this list will able to help you. If you have some tips and tricks that you want to share with all of us. Please leave in comment. : ) Thanks!

Reference
jquery-howto.blogspot.com
How to Decrease Server Issues from Web Hosting Search
learningjquery.com

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

21 comments
Karl Swedberg 15 years ago
Hi there,
Nice article. If I may, I'd like to correct or clarify a few things.
#4. $('#edit-checkbox-id').is(':checked'); : This returns a boolean, so you'll need to use it as an "if" condition.

if ($('#edit-checkbox-id').is(':checked') ) {
/* do something */
}

The "@" symbol for attribute selectors has been deprecated as of jQuery 1.1.4 and removed as of jQuery 1.3. Your "third way" should start like this:

$("input[type=checkbox][checked]").each(

or better yet:

$("[:checkbox]:checked").each(
Reply
Karl Swedberg 15 years ago
Also, the article you cite for #6 is really old, and the information is outdated. In most browsers now $(".myclass"); will be faster than $("ul.myclass"); -- but it's not worth worrying about it, because Sizzle (the new selector engine, as of jQuery 1.3) is still being tweaked and what is faster now may slower in a month. (sorry, couldn't fit everything in one comment with the 800-character limit.)
Reply
kevin Admin 15 years ago
@Karl: thanks for the information. I have updated the article accordingly. Cheers
Reply
vital 15 years ago
@steezin
Yes, sir,
Somehow I fail to see how an actual website performance could possibly depend on looking up some acronyms on Wikipedia or some other theorizings.
Reply
Hieu Pham 15 years ago
Selector for all external links: $("a[href*='http://']:not([href*='"+location.hostname+"'])")
I just think this way much cleaner.
Reply
HaRy... 15 years ago
document.getElementById("#message") .style.removeAttribute("filter");

is wrong...

#message works only in jQ ;)
Reply
kevin Admin 15 years ago
@Hary: hey... haha.. u're right ;)
Reply
vital 15 years ago
Google hosting your jQuery is a 100% bad idea. It is like parking your car at your friends parking lot a few blocks away.
Google occasionally has slowdowns. I have no need for an additional critical point of failure for my websites.
Reply
Joe McCann 15 years ago
@vital

Actually, quite the opposite is true. There is a good chance a user may already have the file cached on their computer, moreover, receiving the file from Google's CDNs are much faster than your webhost or your server.
Reply
vital 15 years ago
@Joe McCann

I says: "Google occasionally has slowdowns"
Joe says: "Actually, quite the opposite is true"
Very well.

"receiving the file from Google's CDNs are much faster than your webhost or your server." - it is time to upgrade your server. In addition, I suggest you pull out your firebug, enable Net panel, play with it over some period of time and get some hard statistical data.

How does the fact that the cached file is from Google make it faster? Hello.
Reply
steezin 15 years ago
@vital

You, sir, need to do some more research. If you believe your website's CDN is comparable to that of google you are mistaken. They have server farms across the globe. Do me a favor and go look up a wikipedia entry on "round trip time (RTT)"

Loading javascript files does not occur asynchronously. By loading jquery through google, you are decreasing your load time by asynchronously loading your includes from multiple server locations.
Reply
vital 15 years ago
I have to backup on my initial claim and apologize to Joe.
"Google hosting your jQuery is a 100% bad idea" - is just my strong opinion.
The fact is that the usefulness of Google hosting your jQuery is debatable. Much more broad statistical data is needed to establish it one way or the other.
My story is... in late 2008 I used Google to host jQuery for two websites, One (~600 pages) I am maintaining on a daily basis the other was actively being developed. In a day or so i noticed occasional slowdowns. It lasted for week or so. So I switched back to my own jQuery hosting and formed my previously expressed opinion. I used only the first (Google official) method.
Still I do no think that adding one more critical dependency on a third party service to you website is a good idea.
Reply
Grunties 15 years ago
Loading jQuery from Google will, every now and then, cause a multiple-second delay in page loading. Ignore the possibility to save yourself a paltry 16k per visitor at your own risk... :)
Reply