jQuery and General Javascript Tips to Improve Your Code

May 19, 2013 · 72 comments

by Lars

jquery-tips

I have published several articles describing the many benefits we can all get from using jquery. Having access to many good plugins, examples and tutorials is important to get great ideas turned into excellent solutions as fast and elegant as possible and that is what jquery is all about. If you use jquery regularly or plan to start using it as more and more web developers tend to do I believe a few fundamentals and best practice tips to improve your jquery code will be worth spending a few minutes on. Please don’t hesitate to post a comment with your own tips and suggestions. Also check out: More jQuery and General Javascript Tips to Improve Your Code


ElegantThemes
ThemeForest

Advertisement

jQuery Tips

#1 – Load the framework from Google Code

Google have been hosting several JavaScript libraries for a while now on Google Code and you may want to load it from them instead of from your server.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>

#2 – Storing Data

Use data method and avoid storing data inside the DOM. Some developers have a habit of storing data in the HTML attributes like fx.:

$('selector').attr('alt', 'data being stored');
// later the data can be retrieved using:
$('selector').attr('alt');

HTML attributes is not meant to store data like that and the “alt” as a parameter name does not really make sense.

The right alternative in most cases is using the data method in jQuery. It allows you to associate data with an element on the page.

$('selector').data('paramtername', 'data being stored');
// then later getting the data with
$('selector').data('paramtername');

This approach allows you to store data with meaningful names and it is more flexible as you can store as much data as you want on any element on the page. For more information about data() and removeData(), see here jQuery internals

One classical use of this is saving the default value of a input field because you want to clear it on focus.

<form id="testform">
 <input type="text" class="clear" value="Always cleared" />
 <input type="text" class="clear once" value="Cleared only once" />
 <input type="text" value="Normal text" />
</form>

$(function() {
 //Go through every input field with clear class using each function
 //(NB! "clear once" is two classes clear and once)
 $('#testform input.clear').each(function(){
   //use the data function to save the data
   $(this).data( "txt", $.trim($(this).val()) );
 }).focus(function(){
   // On focus test for default saved value and if not the same clear it
   if ( $.trim($(this).val()) === $(this).data("txt") ) {
     $(this).val("");
   }
 }).blur(function(){
   // Use blur event to reset default value in field that have class clear
   // but ignore if class once is present
   if ( $.trim($(this).val()) === "" && !$(this).hasClass("once") ) {
     //Restore saved data
     $(this).val( $(this).data("txt") );
   }
 });
});

Demo here

#3 – Use Cheat Sheets

Most people can’t remember a lot of details and even though programmers tend to be better that the average the amount of information they need to have instant access too is devastating. Having a few cheat sheets printed out and placed next to the monitor is a good idea to speed up programming and to improve the code quality.

oscarotero jquery 1.3 (as wallpaper)
javascript-frameworks

jQuery 1.3 Cheat Sheet

Quick reference to all jQuery 1.3 functions and properties. Note that it doesn’t cover any of the UI functionality as this could easily be a whole cheat sheet in and of itself.

CHEAT_SHEETS

#4 – Minimize download time

Most browsers only download one script at the time and if you have several scripts being loaded on every page it can impact your download time.

You can use Dean Edwards service “packer” to compress your scripts and make download faster. You need to maintain a development version and a runtime version as all you in-line comments will be lost. You will find it here.

jquery-tips

Another solution that take this to the extreme is interesting to take a look at. Basically it is a server based PHP script that combine javasctipt files and compress them in a easy to maintain approach. Take a look at and see if you can use the idea and some elements of the concept “Make your pages load faster by combining and compressing javascript and css files“.

#5 – Logging to the Firebug console in jQuery

Firebug is one of my favourite Firefox extensions providing tons of tools in a very usable structure to aid you in HTML+CSS+JavaScript development. Obviously it is worth having just for it’s excellent inspection feature allowing you to jump into the html and css and learn in a visual way what elements of the page is rendered by what code. As a jQuery and general Javascript developer Firefox also has good support for logging in your JavaScript code.

The easiest way to write to the Firebug console looks like this:

console.log("hello world")

jquery-tips

You can pass as many arguments as you want and they will be joined together in a row, like

console.log(2,4,6,8,"foo",bar)

As a jQuery developer it even gets better using a tiny extension that Dominic Mitchell came up with to log any jQuery object to the console .

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};

With this extension you can simply call .log() on the object you are currently addressing fx.:

$('#some_div').find('li.source > input:checkbox')
    .log("sources to uncheck")
    .removeAttr("checked");

#6 – Use ID as Selector whenever possible

Selecting DOM elements using the class attribute is simpler than ever using  jQuery. Even though it is simple it should be avoided whenever possible as as selecting using ID is much faster (In IE the class selector seams to loop through the entire DOM why generally it should be avoided). Selecting elements using IDs is fast because the browsers have the native getElementByID method that jQuery will use for IDs. Selecting classes still requires the DOM to be traversed behind the scene and if it is a large DOM and you make several lookups the performance impact can be significant. Let take a look at this simple html code:

<div id="main">
<form method="post" action="/">
  <h2>Selectors in jQuery</h2>
  ...
  ...
  <input class="button" id="main_button" type="submit" value="Submit" />
</form>
</div>

...
//Selecting the submit button using the class attribute
//like this is much slower than...
var main_button = $('#main .button');

//Selecting the submit button directly using the id like this
var main_button = $('#main_button');

#7 – Use Tags Before Classes

When you are selecting through tags jQuery will use the native browser JavaScript method, getElementsByTagName(). ID is still faster but this is still much faster than selecting with a class name.

<ul id="shopping_cart_items">
  <li><input class="in_stock" name="item" type="radio" value="Item-X" /> Item X</li>
  <li><input class="3-5_days" name="item" type="radio" value="Item-Y" /> Item Y</li>
  <li><input class="unknown" name="item" type="radio" value="Item-Z" /> Item Z</li>
</ul>

It is important to prefix a class with a tag name (here this is “input”) and then it is important to descend from an ID to limit the scope of the selection:

var in_stock = $('#shopping_cart_items input.in_stock');

#8 – Cache jQuery Objects

Caching an object before working with it is essential for performance. You should neverdo like this:

<li>Description: <input type="text" name="description" value="" /></li>
...
$('#shopping_cart_items input.text').css('border', '3px dashed yellow');
$('#shopping_cart_items input.text').css('background-color', 'red');
$('#shopping_cart_items input.text').val("text updated");

In stead cache the object and work on it. The example below should really use chaining but it is just for illustration.

var input_text = $('#shopping_cart_items input.text');
input_text.css('border', '3px dashed yellow');
input_text.css('background-color', 'red');
input_text.val("text updated");

//same with chaining:
var input_text = $('#shopping_cart_items input.text');
input_text
 .css('border', '3px dashed yellow')
 .css('background-color', 'red')
 .val("text updated");

#9 – Bind certain jQuery functions to $(window).load event

Most jQuery code examples and tutorials instruct us to bind our jQuery code to the $(document).ready event. In many cases this is OK but since $(document).ready occurs during page render while objects are still downloading it may cause problems for some types of scripts. Functionality such as binding visual effects and animations, drag and drop, pre-fetching hidden images etc. could benefit from being bound to the $(window).load as it will ensure that all dependant elements are ready for use.

$(window).load(function(){
 // Put your jQuery functions that should only initialize after the page has loaded.
});

#10 – Use Chaining to limit selectors, make the code more simple and elegant

Because JavaScript supports chaining and because it works across line breaks you can structure your code like this. This example first removes a class on an element and then adds another to the same element.

$('#shopping_cart_items input.in_stock')
    .removeClass('in_stock')
    .addClass('3-5_days');

If needed it is really simple and useful as well to create a jQuery function that support chaining.

$.fn.makeNotInStock = function() {
    return $(this).removeClass('in_stock').addClass('3-5_days');
}

$('#shopping_cart_items input.in_stock').makeNotInStock().log();

 

{ 36 comments… read them below or add one }

Meer Anis January 2, 2014 at 6:19 am

It’s obviously a good sharing for all. The beginners will be benefited from here.

Reply

Ashraf December 13, 2012 at 4:26 pm

Wonderful General Java script Tips. thanks

Reply

annesofie December 14, 2012 at 11:32 am

Hi Ashraf, you’re very much welcome. Just glad you found the post relevant.
Best regards, Sofie

Reply

cheap custom jerseys May 19, 2011 at 9:07 am

jQuery and General Javascript Tips to Improve Your Code

Reply

Hosting Best May 13, 2011 at 12:20 pm

Only just recently started getting into JQuery but it really pays off when you get the finished article, thanks for the write up, really useful

Reply

Rokaiya Yeasmin Munni August 5, 2010 at 8:01 am

Wonderful JavaScript tips. Thanks,,,,

Reply

jenifer c April 13, 2010 at 7:57 am
Grant @ portal software February 24, 2010 at 3:49 am

Some very nice and useful optimization tips. It’s hard to go over some old code and optimize it line by line so sometimes it’s just best to start it all from scratch, you can really see a difference after and learn more I think.

Reply

tripwiremag February 24, 2010 at 10:52 am

@Grant, agreed – re-factoring code isn’t that easy – especially languages like JavaScript. Learning new tips for future projects is important though ;)

Reply

Sunny Singh February 21, 2010 at 6:53 pm

I realy don’t see loading jQuery from Google better. There’s not an extremely high chance that the visitor has already downloaded the source, if they didn’t they have to connect to the domain first which may take a while. Not only that, but not everyone have specified the same version of jQuery, which lessens the odds of your site loading faster. If you load it from your own site (gzipped and compressed) including other scripts in the same file, you can achieve much better download speeds than relying on a third-party host.

Reply

Sander Aarts December 16, 2009 at 10:34 pm

Oops, something went wrong.

3rd sentence:
You should use a LABEL ELEMENT for that purpose…

Reply

Sander Aarts December 16, 2009 at 10:29 pm

Thanks for the tips.

The example in #2 is bad practice though. A default value of an input should really be a possible value, not info about is expected to be entered. You should use a for that purpose and JavaScript to position it over the input if you wish. A List Apart had an article about this in 2006: http://www.alistapart.com/articles/makingcompactformsmoreaccessible/
If a default value instead of a label and JavaScript is turned off users first have to delete the value before they can enter their own.

There are many jQuery plugins for the overLabel behavior described in the ALA article. One is mine: http://jlix.net/extensions/jquery/overLabel

Reply

Jordan November 20, 2009 at 9:37 pm

In your example:
var tTab = $(’#tab-main’);
$(tTab+’ div’).show();

tTab is a jQuery object. so (tTab + ‘ div’) is like saying $(’#tab-main’)” div” which isn’t correct.

Instead, you can do tTab.find(‘div’), or tTab.children(‘div’).

Reply

kenan November 20, 2009 at 3:15 pm

Hi,

How can i use caching in situation like:
$(‘#tab-main div’).show();

Im trying:
var tTab = $(‘#tab-main’);
$(tTab+’ div’).show();

….but error…

Thanks

Reply

fxtrade November 19, 2009 at 6:33 am

Thank you very much for sharing. Your information always proves to be useful. I think your post is suitable for everyne, who is interested in valuable resources . I will keep following your posts.

Reply

Jordan October 30, 2009 at 1:16 am

Actually (@Ade) to avoid the SSL error, just use “//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”. Every web browser will ALWAYS access this via the current protocol – if on HTTP, http://, if on HTTPS, https://.

Basically any time you can rely on the SSL certificate to be valid, you should use the double slash when including page resources.

Reply

Sasa Bogdanovic October 28, 2009 at 3:51 pm

While I agree with most of the points, I would:

- take loading the framework from Google Code with the pinch of salt. If you are developing intranet applications in enterprise environment, e.g. reporting systems, there is a high probability that the application would need to be accessed via VPN connections. In this, loading the framework from Google or any other CDN would probably fail as it will not pass VPN authentication.

- practically bind ALL jQuery functions that traverse/manipulate DOM after the document has been loaded, to ensure no JavaScript errors occur due to trying to access elements that haven’t been loaded yet.

Reply

Ade October 28, 2009 at 3:02 pm

People often recommend loading code from Google but I have never noticed anyone mention a potential pitfall of this approach when your site has areas that are protected with an SSL certificate (and thus are accessed via https).

If you load http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js on a secured page, Internet Explorer will pop up a dialog warning the user that some elements of the page are not secure, and will ask if the user wishes to load these elements. This is not at all good for users’ impression of your site and security, and may break your site if they select not to.

So be sure to load the version at https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js on those pages instead.

Reply

chrisweb October 27, 2009 at 7:17 pm

Hello,

You said: “there are several advantages to loading it from them instead of from your server”

Could you please explain which advantages you get by loading the library from google?

chris

Reply

Ian October 26, 2009 at 6:12 pm

in example #7, isn’t it bad form to use a classname starting with a number?

Reply

devcheatsheet October 26, 2009 at 12:57 pm

More jQuery cheat sheets can be found on devcheatsheet.com: http://devcheatsheet.com/tag/jquery/

Reply

András Bártházi October 26, 2009 at 8:06 am

Chris: actually Firebug seems to behave the same as IE8 – maybe because I’m using the latest beta version. So prepare that Firebug’s console object will be available only when the console is visible.

Reply

Cherian October 26, 2009 at 6:10 am

Take a look at the YUI compressor instead of Packer. (http://developer.yahoo.com/yui/compressor/)

Reply

tripwiremag October 26, 2009 at 7:46 am

@Cherian, @Andrew, @Chris: Thanks for the tip and for sharing your experience with YUI and Packer.

@All Thanks for the great feedback it is really appreciated!

Reply

Andrew Hedges October 26, 2009 at 4:11 am

Good list, except for the recommendation to use Edwards’ Packer. YUI Compressor yields nearly as good compression, but far faster script evaluation times. Here’s a convenient online version: http://yui.2clics.net/

Reply

JavaScript Countdown Timer October 26, 2009 at 3:28 am

very cool & good tips, thank you very much for sharing.

Can I share this post on my JavaScript library?

Awaiting your response. Thank

Reply

Chris Brandsma October 26, 2009 at 1:58 am

Unfortunately, I’ve seen issues with Packer and IE6. as much as I would like to ignore that browser, I’m not allowed to. You are better off using YUI’s minimizer instead.

On the log function as well, that requires Firebug to be there (IE 8 also does the same thing, but the console has be be enabled to work). I tend to wrap my logging calls to make sure the console is actually there. Worse case your javascript will just stop working for no apparent reason.

Also, Microsoft has also created a CDN for JQuery, JQuery.Validator, and the Microsoft Ajax libraries. So google is not your only option there.
http://weblogs.asp.net/scottgu/archive/2009/09/15/announcing-the-microsoft-ajax-cdn.aspx

Reply

Vince October 26, 2009 at 1:35 am

Thanks for the post. I’ve been using JQuery for a while, and could really use the pointers you suggested.

Reply

sunpietro October 25, 2009 at 7:24 pm

Thanks a lot for that article. It is useful :)
Keep on writing similar articles :)

Reply

Inside the Webb October 25, 2009 at 5:06 pm

Tripwire Mag has some of the best articles I’ve seen in a long time, props guys. If you’d ever be interested in having an interview on my blog, check it out and definitely let me know ( link is http://www.insidethewebb.com/ )

Reply

András Bártházi October 25, 2009 at 1:53 pm

About the example of the 2nd tip: using the plain, old .defaultValue for resetting to the initial value is much better and clean solution. However thanks for sharing the tip for using .data(), I haven’t read about this before, and I will definitely use it.

Reply

iresha October 25, 2009 at 10:47 am

Excellent post. This has really opened a new dimension for me

Reply

clippingimages October 25, 2009 at 8:18 am

WoW :) Great tips to improve jquery and javascript code. Really awesome and i was searching few of these solutions. Really thanks for sharing this nice tips to help me.

Reply

FP October 24, 2009 at 2:14 pm

Thanks for this great post!
Some of the points are really useful and I didn’t know some of the details.

About the 1st point, loading jQuery from Google, can you elaborate a bit more? I understand that if a website load it from Google there’s an high probability that the .js is already cached. But this is true only for internet applications. Do you see any advantage of linking to Google also from intranet-based apps?

Reply

tripwiremag October 24, 2009 at 7:10 pm

@FP: From an Intranet application I would not pull scripts from google or another external source unless they are only commercially available from there and unless the source has a well defined SLA on availability. Placing the script on an internal server would probably be more effective in terms of loading as well.

Reply

Masoud October 24, 2009 at 9:54 am

nice tips.

thanks for sharing ;)

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

{ 36 trackbacks }

Previous post:

Next post:


Web Analytics