Register now or login here to start promoting your blog and your favourite articles.
jQuery Tips and Tricks II
7 Apr 2009 - 19 Comments
jQuery Tips and Tricks Part 2! Obviously, one post is simply not enough. 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.
Author: kevin | Source: queness

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

Copyright & Usage

The effects and techniques demonstrated in tutorials on Queness can be used in whatever manner you wish without attribution. You cannot copy whole tutorials (unless permission is given), either in English or translated to another language.

Share This Post to Support Me! :)


Comments

Karl Swedberg on 6 Apr 2009 says:
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(
Karl Swedberg on 6 Apr 2009 says:
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.)
kevin on 6 Apr 2009 says:
@Karl: thanks for the information. I have updated the article accordingly. Cheers
Hieu Pham on 7 Apr 2009 says:
Selector for all external links: $("a[href*='http://']:not([href*='"+location.hostname+"'])")
I just think this way much cleaner.
HaRy... on 7 Apr 2009 says:
document.getElementById("#message") .style.removeAttribute("filter");

is wrong...

#message works only in jQ ;)
kevin on 7 Apr 2009 says:
@Hary: hey... haha.. u're right ;)
vital on 7 Apr 2009 says:
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.
Joe McCann on 7 Apr 2009 says:
@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.
vital on 7 Apr 2009 says:
@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.
steezin on 7 Apr 2009 says:
@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.
vital on 7 Apr 2009 says:
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.
vital on 7 Apr 2009 says:
@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.
Grunties on 8 Apr 2009 says:
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... :)
Alexander on 8 Apr 2009 says:
Tip 9 doesn't work for me. In IE7 ist's the same ugly effect like before.
ZK@Web Marketing Blog on 20 Jun 2009 says:
What you probably should look at doing is showing the first panel by default so it is still visible without Javascript and then rather than have the links href set to just '#' make them link to pages showing the information from each panel.
Rob @ Web Design Talk on 12 Aug 2009 says:
Like the tip about the fadein rendering in IE - always wondered about that. I used to get that problme in IE7 aswell.

@Grunties: there are loads of reasons to left Google host your JQuery, with the main being the fact that you're in essence getting CDN for free.

Rob @ Web Design Talk on 12 Aug 2009 says:
Like the tip about the fadein rendering in IE - always wondered about that. I used to get that problme in IE7 aswell.

@Grunties: there are loads of reasons to left Google host your JQuery, with the main being the fact that you're in essence getting CDN for free.
Shahriar Hyder on 24 Sep 2009 says:
Excellent collection of jQuery Tips and Tricks mate. I have also linked to yours from my blog post below where I am trying to collect the most useful and common jQuery code snippets for JavaScript over the web. Here is the title and the link to the jQuery link compilation endeavor:


Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance


http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/

Leave a comment

http://
Subscribe RSS Subscribe RSS, Keep yourself updated with queness latest posts!
Pixel Crayons Buy and Sell Flash Buy and Sell Flash

Buy wholesale computers directly from China at DHgate.com

Discover the tools to build your e-Commerce Site with Netfirms

  •  
  •  
  •  
  •  
  •  

Community News

Recent Comments

Random Posts


View all posts and news Back to top

About the Author

A web designer and developer who is passionate and keen on contributing to the web development industry. Feel free to say hi to me, or follow me on twitter.

Kevin Liew

Partner

  • Web and Designers
  • CSS Style
  • PV.M Garage Blogzine - (Italian)
  • TutsValley
  • Designrfix
  • CoolVibe
  • Web Developer Juice
  • Denbagus
  • Web Hosting Secret Revealed
  • PSD to HTML Conversion
  • BlueHost