Quantcast

jQuery and General Javascript Tips to Improve Your Code

Sat, Oct 24, 2009

Development, Javascript, Tutorials

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



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();

Related posts

  1. More jQuery and General Javascript Tips to Improve Your Code This post pick up on my previous post “jQuery...
  2. 10 Useful jQuery Techniques to Improve Your Code jQuery is known for making things that where hard...
  3. 30+ jQuery Plugins to Improve Usability and Look and Feel of HTML Forms Forms are essential for communication online and they are...
  4. 75+ Top jQuery Plugins to improve Your HTML Forms jQuery makes it easier and simpler to provide your...
  5. How to: jQuery Driven Social Bookmark Counters In this article tripwire magazine provides a tutorial on how...

Please subscribe to tripwire magazines rss feed

Please remember to share this post!

29 Comments For This Post

  1. Masoud Says:

    nice tips.

    thanks for sharing ;)

  2. FP Says:

    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?

  3. tripwiremag Says:

    @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.

  4. clippingimages Says:

    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.

  5. iresha Says:

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

  6. András Bártházi Says:

    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.

  7. Inside the Webb Says:

    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/ )

  8. sunpietro Says:

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

  9. Vince Says:

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

  10. Chris Brandsma Says:

    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

  11. JavaScript Countdown Timer Says:

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

    Can I share this post on my JavaScript library?

    Awaiting your response. Thank

  12. Andrew Hedges Says:

    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/

  13. Cherian Says:

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

  14. tripwiremag Says:

    @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!

  15. András Bártházi Says:

    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.

  16. devcheatsheet Says:

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

  17. Ian Says:

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

  18. chrisweb Says:

    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

  19. Ade Says:

    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.

  20. Sasa Bogdanovic Says:

    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.

  21. Jordan Says:

    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.

  22. fxtrade Says:

    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.

  23. kenan Says:

    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

  24. Jordan Says:

    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’).

  25. Sander Aarts Says:

    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

  26. Sander Aarts Says:

    Oops, something went wrong.

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

  27. Sunny Singh Says:

    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.

  28. Grant @ portal software Says:

    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.

  29. tripwiremag Says:

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

30 Trackbacks For This Post

  1. jQuery and General Javascript Tips to Improve Your Code | My Money and Finance Blog @ Smrits Says:

    [...] practice tips to improve your jquery code will be worth spending a few min See original here:  jQuery and General Javascript Tips to Improve Your Code Share and [...]

  2. jQuery and General Javascript Tips to Improve Your Code Says:

    [...] here: jQuery and General Javascript Tips to Improve Your Code Finding An Affordable SEO Service» Best Web Hosting Reviews and Ratings Online Life is [...]

  3. Tweets that mention jQuery and General Javascript Tips to Improve Your Code | tripwire magazine -- Topsy.com Says:

    [...] This post was mentioned on Twitter by Meng To, Web Design. Web Design said: jQuery and General Javascript Tips to Improve Your Code: I have published several articles describing the many.. http://bit.ly/4t4bS5 [...]

  4. jQuery and General Javascript Tips to Improve Your Code | tripwire … | PhotoShopped Says:

    [...] Read more: jQuery and General Javascript Tips to Improve Your Code | tripwire … [...]

  5. jQuery and General Javascript Tips to Improve Your Code | tripwire … Says:

    [...] is the original:  jQuery and General Javascript Tips to Improve Your Code | tripwire … SHARETHIS.addEntry({ title: "jQuery and General Javascript Tips to Improve Your Code | tripwire [...]

  6. jQuery and General Javascript Tips to Improve Your Code | Adobe Tutorials Says:

    [...] 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 min More here: jQuery and General Javascript Tips to Improve Your Code [...]

  7. Webby Scripts jQuery and General Javascript Tips to Improve Your Code Says:

    [...] rest is here: jQuery and General Javascript Tips to Improve Your Code [...]

  8. uberVU - social comments Says:

    Social comments and analytics for this post…

    This post was mentioned on Twitter by Designrss: jQuery and General Javascript Tips to Improve Your Code http://bit.ly/2JDR1J...

  9. jQuery and General Javascript Tips to Improve Your Code | TopRoundups Says:

    [...] jQuery and General Javascript Tips to Improve Your Code Submitted by Editorial Team [...]

  10. links for 2009-10-24 | Gzone Says:

    [...] jQuery and General Javascript Tips to Improve Your Code | tripwire magazine (tags: jquery javascript tutorials) [...]

  11. jQuery and General Javascript Tips to Improve Your Code | tripwire magazine « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit Says:

    [...] jQuery and General Javascript Tips to Improve Your Code | tripwire magazinetripwiremagazine.com [...]

  12. Notable Tech Posts – 2009.10.25 | The Life of Lew Ayotte Says:

    [...] jQuery and general Javascript tips to improve your code var addthis_pub = 'lewayotte'; var addthis_language = 'en';var addthis_options = 'email, favorites, digg, delicious, myspace, google, facebook, reddit, live, more'; [...]

  13. eKini: Web Developer Blog » jQuery Tips Says:

    [...] complete article can be found in Tripwire Magazine. Subscribe to comments Comment | Trackback | Post Tags: jquery, jquery [...]

  14. ??????? » [Web] ???? Says:

    [...] jQuery and General Javascript Tips to Improve Your Code [...]

  15. Vagner Rodrigues (slowtux) 's status on Tuesday, 27-Oct-09 15:07:13 UTC - Identi.ca Says:

    [...] http://www.tripwiremagazine.com/tutorials/tutorials/jquery-and-general-javascript-tips-to-improve-y... a few seconds ago from seesmic [...]

  16. jQuery and General Javascript Tips to Improve Your Code | Design Newz Says:

    [...] jQuery and General Javascript Tips to Improve Your Code [...]

  17. More jQuery and General Javascript Tips to Improve Your Code | tripwire magazine Says:

    [...] This is handy if you quickly want to try out an idea for a script with the latest version. As you may know you can also load jQuery from ajax.googleapis.com as shown in #1 – Load the framework from Google Code here. [...]

  18. More jQuery and General Javascript Tips to Improve Your Code | Programming Blog Says:

    [...] post pick up on my previous post “jQuery and General Javascript Tips to Improve Your Code” and provides additional nice to know tips for jQuery developers. jQuery is popular for a [...]

  19. More jQuery and General Javascript Tips to Improve Your Code | Master Design Says:

    [...] This is handy if you quickly want to try out an idea for a script with the latest version. As you may know you can also load jQuery from ajax.googleapis.com as shown in #1 – Load the framework from Google Code here. [...]

  20. Artículos destacados, octubre de 2009 | cambrico.net Says:

    [...] para mejorar tu código JQuery, en tripwire (en [...]

  21. jQuery Kullan?m?n?z? Geli?tirmek için Öneriler | CETURK Says:

    [...] Çelik kurtmancelik.wordpress.com Kaynak: http://www.tripwiremagazine.com/tutorials/tutorials/jquery-and-general-javascript-tips-to-improve-yo... Etiketler: JQuery, Kurtman [...]

  22. jQuery and General Javascript Tips to Improve Your Code | pc-aras Says:

    [...] on. Please don’t hesitate to post a comment with your own tips and suggestions. continue  :: tripwiremagazine// Share and [...]

  23. 10 Useful jQuery Techniques to Improve Your Code | Programming Blog Says:

    [...] jQuery and General Javascript Tips to Improve Your Code [...]

  24. 10 Useful jQuery Techniques to Improve Your Code | Afif Fattouh - Web Specialist Says:

    [...] jQuery and General Javascript Tips to Improve Your Code [...]

  25. uberVU - social comments Says:

    Social comments and analytics for this post…

    This post was mentioned on Twitter by deduccion: LINKS jQuery Tips Code http://www.tripwiremagazine.com/2009/10/jquery-and-general-javascript-tips-to-improve-your-code.html...

  26. jQuery and General Javascript Tips to Improve Your Code | Dev Loom Says:

    [...] jQuery and General Javascript Tips to Improve Your Code Via / Script & Style [...]

  27. jQuery tips - storing data | stoimen.com/blog Says:

    [...] was reading an article where the author says it is not a good practice to store data in the DOM. Indeed this is a bad [...]

  28. Linkhub – Woche 07-2010 « pehbehbeh Says:

    [...] jQuery and General JavaScript Tips to Improve Your Code [...]

  29. Notable Tech Posts – 2010.02.21 | The Life of Lew Ayotte Says:

    [...] jQuery and general JavaScript tips to improve your code [...]

  30. Top 10 Best JavaScript Books that Beginners should Read — iooo Says:

    [...] jQuery and General Javascript Tips to Improve Your Code I have published several articles describing the many benefits… [...]

Leave a Reply