JavaScript
Article

10 Tips to improve your jQuery

By Sam Deering

There’s jQuery almost everywhere, you can find it on famous websites available today including social networking websites, micro blogs, etc. jQuery is indeed cool and very useful, but sometimes it’s best to see a different flavor or another side of it. Or perhaps make improvements for it.

Improving jQuery would make your website load faster and do similar things that will help your website stand out. This could include a jQuery script or code via Google codes and stuffs like that. Like I said, it’s best to improve or edit a jQuery plugin or syntax that will be used by your website to make it more prominent.

What I have here is a list of ten tips to improve your jQuery.

1. Shortcut for “Ready” event

Are you tired of typing this?

$(document).ready(function (){
		// your code
	});

Well you can make a shortcut for it, try this:

$(function (){
		// your code
	});

2. Element Checker

Be sure to check if the element really exists on the page before you manipulate it. Use this simple but not obvious code:

if ($('#myDiv).length) {
		// your code
	}

3. Properly rename your jQuery object when using another framework

Use the noconflict() jQuery function to take control of $ back and allow yourself to set your own variable name.

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

4. Compress your jQuery scripts

A big project probably means a lot of jQuery plugin usage too. But be aware that this might slow down your page, so you should compress all of your jQuery by using Packer by Dean Edwards. It’s a web based javascript compressor.

5. Minimize DOM Manipulation

Insertion operations of DOM such as .prepend() .append() .wrap() and .after() would really slow things down. You could make codes faster; all you need to do is build the list by using concatenation then after that, a single use of function to add them to your list that’s unordered like .html() is much quicker.

Example:

var myList = $('#myList');

	for (i=0; i<1000; i++){
		myList.append('This is list item ' + i);
	}
	That example is relatively slow, but if you build the list item as a string and use the html method to do the insertion. You might want to try the following instead:
	Example:
	var myList = $('.myList');
	var myListItems = '';

	for (i = 0; i < 1000; i++) {
		myListItems += '
  • This is list item ' + i + ''; } myList.html(myListItems);
  • That would make the page load faster!

    6. Give Context for your Selectors

    Normally if you use a selector like $(‘.myDiv’) DOM would definitely traversed, which depends on the page could be expensive.
    Performing selections would make the jQuery take a second parameter.
    jQuery( expression, context )
    By putting context into a single selector, you would give that selector an element to start with so it doesn’t have to traverse the whole of the DOM.

    Before:

    var selectedItem = $('#listItem' + i);

    After:

    var selectedItem = $('#listItem' + i, $('.myList'));

    That should speed things up!

    7. Proper usage of animation

    Animation is the core power of jQuery. It’s really cool and provides very eye catchy effects.
    jQuery’s .animate() method is very easy to use and powerful. If you look at the codes internally those methods are just shortened and uses the .animate() function.

    Example:

    slideDown: function(speed,callback){
    		return this.animate({height: "show"}, speed, callback);
    	},
    
    	fadeIn: function(speed, callback){
    		return this.animate({opacity: "show"}, speed, callback);
    	}

    The animate() function simply changes the element’s CSS properties such as height, width, color, opacity, background-color, etc.

    Example:

    $('#myList li').mouseover(function() {
    		$(this).animate({"height": 100}, "slow");
    	});

    Unlike jQuery other functions, animations are automatically queued. If you want to execute another animation when the first animation is finished then just call the animate method twice.
    Example:

    $('#myBox').mouseover(function() {
    		$(this).animate({ "width": 200 }, "slow");
    		$(this).animate({"height": 200}, "slow");
    	});

    If you want multiple animations, do it this way:

    $('#myBox').mouseover(function() {
    		$(this).animate({ "width": 200, "height": 200 }, "slow");
    	});

    8. Do your own Selectors

    jQuery has many built-in selectors for selection of elements by ID, tag, attribute and many more. But what would you do if you need to select elements based on something else wherein jQuery doesn’t have a selector.
    Probably, you would add classes to the lements from the beginning and use those to select them. But it beats the purpose of jQuery’s ease of extension to add new selectors.

    Example:

    $.extend($.expr[':'], {
    		over100pixels: function(a) {
    			return $(a).height() > 100;
    		}
    	});
    $('.box:over100pixels').click(function() {
    		alert('The element you clicked is over 100 pixels high');
    	});

    Creation of custom selector is in the first block of code which finds any elements that’s more than 100 pixels tall.

    9. Speed up content load for SEO benefits

    If you think that if you neaten up your HTML code it would make your page load faster. You are right, search spiders is too lazy to load whole code using an AJAX request after the rest of the page has loaded. User can start browsing right away and spiders only see the content you wish them to index.

    Example:

    $('#forms').load('content/headerForms.html', function() {
    		// Code here runs once the content has loaded
    		// Put all your event handlers etc. here.
    	});

    10. Use CHEAT SHEET

    Getting tired of jQuery tips? Here are some great cheat sheets available for most languages! It’s a printable jQuery functions on an A4 sheet for your own reference.

    http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/
    http://colorcharge.com/jquery/

    Free Guide:

    7 Habits of Successful CTOs

    "What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

    • http://www.collegescholarships-tips.org college scholarship

      Nice site, nice and easy on the eyes and great content too.

    • Bojidar Marinov

      on “2. Element Checker” there is an apostrophe missing…

    Recommended
    Sponsors
    Because We Like You
    Free Ebooks!

    Grab SitePoint's top 10 web dev and design ebooks, completely free!

    Get the latest in JavaScript, once a week, for free.