jQuery Tips and Tricks II

jQuery Tips and Tricks II


jQuery Tips and Tricks II

 

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

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

21 comments

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

is wrong...

#message works only in jQ ;) Reply
kevin Admin
Tue, 7th April 2009
@Hary: hey... haha.. u're right ;) Reply
vital
Tue, 7th April 2009
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
Tue, 7th April 2009
@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
Tue, 7th April 2009
@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
Tue, 7th April 2009
@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
Tue, 7th April 2009
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
Wed, 8th April 2009
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
Alexander
Wed, 8th April 2009
Tip 9 doesn't work for me. In IE7 ist's the same ugly effect like before. Reply
ZK@Web Marketing Blog
Sat, 20th June 2009
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. Reply
Rob @ Web Design Talk
Wed, 12th August 2009
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.

Reply
Rob @ Web Design Talk
Wed, 12th August 2009
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. Reply
Shahriar Hyder
Thu, 24th September 2009
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/ Reply
molokoloco
Tue, 23rd February 2010
Some very good advices.. but always need some more ;)

That not well explained but i'm index and build some jQuery tips here http://code.google.com/p/molokoloco-coding-project/wiki/JavascriptJquery Reply
Web hosting
Thu, 15th April 2010
Good comment this "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
london builder
Mon, 29th November 2010
Great tips. Many thanks;) Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement