25 Ways To Build Better jQuery Web Applications

download 25 Ways To Build Better jQuery Web Applications

of 19

Transcript of 25 Ways To Build Better jQuery Web Applications

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    1/19

    25 Essential Tips for better jQueryWeb Applications

    addyosmani.com

    Table of Contents

    1. Load the framework from Google Code

    2. Use a cheat sheet

    3. Combine all your scripts and minify them

    4. Use Firebug's excellent console logging facilities 5. Keep selection operations to a minimum by caching

    6. Keep DOM manipulation to a minimum

    7. Wrap everything in a single element when doing any kind of DOM insertion

    8. Use IDs instead of classes wherever possible

    9. Give your selectors a context

    10. Use chaining properly

    11. Learn to use animate properly

    12. Learn about event delegation

    13. Use classes to store state

    14. Even better, use jQuery's internal data() method to store state

    15. Write your own selectors 16. Streamline your HTML and modify it once the page has loaded

    17. Lazy load content for speed and SEO benefits

    18. Use jQuery's utility functions

    19. Use noconflict to rename the jquery object when using other frameworks

    20. How to tell when images have loaded

    21. Always use the latest version

    22. How to check if an element exists

    http://www.addyosmani.com/http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip1http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip2http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip2http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip3http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip4http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip4http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip5http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip5http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip6http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip6http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip7http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip7http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip8http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip8http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip9http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip9http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip10http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip11http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip12http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip13http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip14http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip15http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip16http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip17http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip18http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip19http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip20http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip21http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip22http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip1http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip2http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip3http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip4http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip5http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip6http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip7http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip8http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip9http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip10http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip11http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip12http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip13http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip14http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip15http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip16http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip17http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip18http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip19http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip20http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip21http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip22http://www.addyosmani.com/
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    2/19

    23. Add a JS class to your HTML attribute

    24. Return 'false' to prevent default behaviour

    25. Shorthand for the ready event

    1. Load the framework from Google Code

    Google have been hosting several JavaScript libraries for a while now on Google Code and there areseveral advantages to loading it from them instead of from your server. It saves on bandwidth, it'll load very

    quickly from Google's CDN and most importantly it'll already be cached if the user has visited a site whichdelivers it from Google Code.

    This makes a lot of sense. How many sites out there are serving up identical copies of jQuery that aren'tgetting cached? It's easy to do too...

    1. 2. 3.4. // Load jQuery5. google.load("jquery", "1.2.6");

    6.7. google.setOnLoadCallback(function() {8. // Your code goes here.9. });10.11.

    Or, you can just include a direct reference like this...

    1.

    Full instructions here

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip24http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip25http://code.google.com/apis/ajaxlibs/documentation/index.htmlhttp://code.google.com/apis/ajaxlibs/documentation/index.htmlhttp://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip23http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip24http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip25http://code.google.com/apis/ajaxlibs/documentation/index.html
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    3/19

    2. Use a cheat sheet

    Not just a jQuery tip, there are some great cheat sheets out there for most languages. It's handy havingevery function on a printable A4 sheet for reference and luckily these guys have produced a couple of niceones..

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

    3. Combine all your scripts and minify them

    OK, a general JavaScript tip here. But any big project that uses lots of jQuery probably uses lots of plugins(this site uses easing, localScroll, lightbox and preload) so it's usually applicable.

    Browsers can't load scripts concurrently (well, most can't, yet), which means that if you've got severalscripts downloading one at a time then you're really slowing down the loading of your page. So, assumingthe scrips are being loaded on every page then you should consider combining them into one long scriptbefore deploying.

    Some of the plugins will already be minified, but you should consider packing your scripts and any thataren't already. It only takes a few seconds. I'm personally a fan ofPacker by Dean Edwards

    4. Use Firebug's excellent console logging facilities

    If you haven't already installed Firebug then you really should. Aside from many other useful features suchas allowing you to inspect http traffic and find problems with your CSS it has excellent logging commandsthat allow you to easily debug your scripts.

    Here's a full explanation of all of it's features

    My favourite features are "console.info", which you can use to just dump messages and variables to thescreen without having to use alert boxes and "console.time" which allows you to easily set up a timer towrap a bunch of code and see how long it takes. They're all really easy to use too...

    1. console.time('create list');2.3. for (i = 0; i < 1000; i++) {4. var myList = $('.myList');

    http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/http://colorcharge.com/jquery/http://colorcharge.com/jquery/http://dean.edwards.name/packer/http://dean.edwards.name/packer/http://getfirebug.com/console.htmlhttp://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/http://colorcharge.com/jquery/http://dean.edwards.name/packer/http://getfirebug.com/console.html
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    4/19

    5. myList.append('This is list item ' + i);6. }7.8. console.timeEnd('create list');

    In this instance I've deliberately written some very inefficient code! In the next few tips I'll show you howwe can use the timer to show some improvements which can be made.

    5. Keep selection operations to a minimum by caching

    jQuery selectors are awesome. They make selecting any element on the page incredibly simple, butinternally they have to do a fair amount of work and if you go mad with them you might find things startingto get pretty slow.

    If you're selecting the same element time and time again (in a loop for example) then you can just select itonce and keep it in memory while you manipulate it to your heart's content. Take the following examplewhere we add items to an unordered list using a loop.

    1. for (i = 0; i < 1000; i++) {2. var myList = $('.myList');3. myList.append('This is list item ' + i);4. }

    That takes 1066 milliseconds on my PC in Firefox 3 (imagine how long it would IE6!), which is prettyslow in JavaScript terms. Now take a look at the following code where we use the selector just once.

    1. var myList = $('.myList');2.3. for (i = 0; i < 1000; i++) {4. myList.append('This is list item ' + i);5. }

    That only takes 224 milliseconds, more than 4x faster, just by moving one line of code.

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    5/19

    6. Keep DOM manipulation to a minimum

    We can make the code from the previous tip even faster by cutting down on the number of times we insertinto the DOM. DOM insertion operations like .append() .prepend() .after() and .wrap() are relatively costlyand performing lots of them can really slow things down.

    All we need to do is use string concatenation to build the list and then use a single function to add them toyour unordered list like .html() is much quicker. Take the following example...

    1. var myList = $('#myList');2.3. for (i=0; i

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    6/19

    DIV) then we're effectively only inserting 1 tag, not 1000, which seems to be much quicker. Like this...

    1. var myList = $('.myList');2. var myListItems = '';3. 4. for (i = 0; i < 1000; i++) {5. myListItems += 'This is list item ' + i + '';6. }7.8. myListItems += '';9. myList.html(myListItems);

    The time is now only 19 milliseconds, a massive improvement, 50x faster than our first example.

    8. Use IDs instead of classes wherever possible

    jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it'stempting to use classes much more liberally than before. It's still much better to select by ID thoughbecause jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do anyof it's own DOM traversal, which is much faster. How much faster? Let's find out.

    I'll use the previous example and adapt it so each LI we create has a unique class added to it. Then I'll loopthrough and select each one once.

    1. // Create our list2. var myList = $('.myList');3. varmyListItems = '';4.5. for (i = 0; i < 1000; i++) {6. myListItems += 'This is a list item';7. }8.

    9. myListItems += '';10. myList.html(myListItems);11.12. // Select each item once13. for (i = 0; i < 1000; i++) {14. var selectedItem = $('.listItem' + i);15. }

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    7/19

    Just as I thought my browser had hung, it finished, in 5066 milliseconds (over 5 seconds). So i modified thecode to give each item an ID instead of a class and then selected them using the ID.

    1. // Create our list

    2. var myList = $('.myList');3. var myListItems = '';4.5. for (i = 0; i < 1000; i++) {6. myListItems += 'This is a list item';7. }8.9. myListItems += '';10. myList.html(myListItems);11.12. // Select each item once

    13. for (i = 0; i < 1000; i++) {14. var selectedItem = $('#listItem' + i);15. }

    This time it only took 61 milliseconds. Nearly 100x faster.

    9. Give your selectors a context

    By default, when you use a selector such as $('.myDiv') the whole of the DOM will be traversed, whichdepending on the page could be expensive.

    The jQuery function takes a second parameter when performing a selection.

    jQuery( expression, context )

    By providing a context to the selector, you give it an element to start searching within so that it doesn't haveto traverse the whole of the DOM.

    To demonstrate this, let's take the first block of code from the tip above. It creates an unordered list with1000 items, each with an individual class. It then loops through and selects each item once. You'llremember that when selecting by class it took just over 5 seconds to select all 1000 of them using thisselector.

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

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    8/19

    I then added a context so that it was only running the selector inside the unordered list, like this...

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

    It still took 3818 milliseconds because it's still horribly inefficient, but that's more than a 25% speedincrease by making a small modification to a selector.

    10. Use chaining properly

    One of the coolest things about jQuery is it's ability to chain method calls together. So, for example, if youwant to switch the class on an element.

    1. $('myDiv').removeClass('off').addClass('on');

    If you're anything like me then you probably learned that in your first 5 minutes of reading about jQuerybut it goes further than that. Firstly, it still works across line breaks (because jQuery = JavaScript), whichmeans you can write neat code like this...

    1. $('#mypanel')2. .find('TABLE .firstCol')3. .removeClass('.firstCol')4. .css('background' : 'red')5. .append('This cell is now red');

    Making a habit of using chaining automatically helps you to cut down on your selector use too.

    But it goes further than that. Let's say that you want to perform several functions on an element but one ofthe first functions changes the element in some way, like this...

    1. $('#myTable').find('.firstColumn').css('background','red');

    We've selected a table, drilled down to find cells with a class of "firstColumn" and coloured them in red.

    Let's say we now want to colour all the cells with a class of "lastColumn" blue. Because we've used thefind() funciton we've filtered out all the cells that don't have a class of "firstColumn" so we need to use theselector again to get the table element and we can't continue chaining, right? Luckily jQuery has an end()

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    9/19

    function which actually reverts back to the previous unaltered selection so you can carry on chaining, likethis...

    1. $('#myTable')2. .find('.firstColumn')

    3. .css('background','red')4. .end()5. .find('.lastColumn')6. .css('background','blue');

    It's also easier than you might think to write your own jQuery function which can chain. All you have to dois write a function which modifies an element and returns it.

    1. $.fn.makeRed = function() {2. return $(this).css('background', 'red');3. }4.5. $('#myTable').find('.firstColumn').makeRed().append('hello');

    How easy was that?

    11. Learn to use animate properly

    When I first started using jQuery I loved the fact that it was easy to use the pre-defined animations likeslideDown() and fadeIn() to get some really cool effects incredibly easy. It's easy to take things furtherthough because jQuery's animate() method is very easy to use and very powerful. In fact, is you look at thejQuery source code you'll see that internally those methods are just shortcuts which use the animate()function.

    1. slideDown: function(speed,callback){2.

    returnthis.animate({height: "show"}, speed, callback);3. },4.5. fadeIn: function(speed, callback){6. returnthis.animate({opacity: "show"}, speed, callback);7. }

    The animate() method simply takes any CSS style and smoothly transitions it from one value to another.

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    10/19

    So, you can change the width, height, opacity, background-color, top, left, margin, color, font-size, anythingyou want.

    This is how easy it is to animate all your menu items grow to 100 pixels high when you roll over them.

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

    Unlike other jQuery functions, animations are automatically queued, so if you want to run a secondanimation once the first is finished then just call the animate method twice, no callback necessary.

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

    4. });

    If you want the animations to happen concurrently then just put both styles in the params object of a singlecall, like this...

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

    You can animate any property that's numeric. You can also download plugins to help you animateproperties that aren't, likecolors and background colors

    12. Learn about event delegation

    jQuery makes it easier than ever to attach events to elements in the DOM unobtrusively, which is great, butadding too many events is inefficient. Event delegation allows you to add less events to achieve the sameresult in many situations. The best way to illustrate this is with an example...

    1. $('#myTable TD').click(function(){2. $(this).css('background', 'red');3. });

    http://plugins.jquery.com/project/colorhttp://plugins.jquery.com/project/color
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    11/19

    A simple function which turns cells in a table red when you click on them. Let's say that you've got a gridwith 10 columns and 50 rows though, that's 500 events bound. Wouldn't it be neater if we could just attacha single event to the table and when the table is clicked have the event handler work out which cell wasclicked before turning it red?

    Well that's exactly what event delegation is and it's easy to implement...

    1. $('#myTable').click(function(e) {2. var clicked = $(e.target);3. clicked.css('background', 'red');4. });

    'e' contains information about the event, including the target element that actually received the click. All wehave to do is inspect it to see which cell was actually clicked. Much neater.

    Event delegation has another benefit. Normally, When you bind a handler to a collection of elements it getsattached to those elements and those elements only. If you add new elements to the DOM which wouldhave been matched by the selector then they don't have the event handler bound to them (are you followingme?) then nothing will happen.

    When using event delegation you can add as many matching elements to the DOM as you like after theevent is bound and they work too.

    13. Use classes to store state

    This is the most basic way of storing information about a block of html. jQuery is great at manipulatingelements based upon their classes, so if you need to store information about the state of an element thenwhy not add an extra class to store it?

    Here's an example. We want to create an expanding menu. When you click the button we want the panel toslideDown() if it's currently closed, or slideUp() if it's currently open. We'll start with the HTML

    1.

    2. 3. click me4. 5. 6. 7. Menu item 18. Menu item 29. Menu item 3

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    12/19

    10. 11. 12.

    Very simple! We've just added an extra class to the wrapper div which serves no other purpose other than to

    tell us the state of the item. So all we need is a click event handler which performs slideUp() orslideDown() on the corresponding panel when the button is clicked.

    1. $('.button').click(function() {2.3. var menuItem = $(this).parent();4. var panel = menuItem.find('.panel');5.6. if(menuItem.hasClass("expanded")) {7. menuItem.removeClass('expanded').addClass('collapsed');

    8. panel.slideUp();9. }10. elseif(menuItem.hasClass("collapsed")) {11. menuItem.removeClass('collapsed').addClass('expanded');12. panel.slideDown();13. }14. });

    That's a very simple example, but you can add extra classes for storing all sorts of information about anelement or HTML fragment.

    However, in all but simple cases it's probably better to use the next tip.

    14. Even better, use jQuery's internal data() method to

    store state

    It's not very well documented for some reason but jQuery has an internal data() method which can be usedto store information in key/value pairs against any DOM element. Storing a piece of data is as simple asthis...

    1. $('#myDiv').data('currentState', 'off');

    We can amend the example from the previous tip. We'll use the same HTML (with the "expanded" class

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    13/19

    removed) and use the data() function instead.

    1. $('.button').click(function() {2. 3. var menuItem = $(this).parent();4. var panel = menuItem.find('.panel');5.6. if(menuItem.data('collapsed')) {7. menuItem.data('collapsed', false);8. panel.slideDown();9. }10. else {11. menuItem.data('collapsed', true);12. panel.slideUp();13. }14. });

    I'm sure you'll agree this is much neater. For more information about data() and removeData(), see thispage...

    jQuery internals

    15. Write your own selectors

    jQuery has loads of built-in selectors for selecting elements by ID, class, tag, attribute and many more. Butwhat do you do when you need to select elements based upon something else and jQuery doesn't have aselector?

    Well, one answer would be to add classes to the elements from the start and use those to select them, but itturns out that it's not hard to extend jQuery to add new selectors.

    The best way to demonstrate is with an example.

    1.

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

    http://docs.jquery.com/Internalshttp://docs.jquery.com/Internals
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    14/19

    9. });

    The first block of code creates a custom selector which finds any element that is more than 100 pixels tall.The second block just uses it to add a click handler to all those elements.

    I won't go into any more detail here but you can imagine how powerful this is and if you search google for"custom jquery selector" you'll find loads of great examples.

    16. Streamline your HTML and modify it once the page

    has loaded

    The title might not make a lot of sense but this tip can potentially neaten up your code, reduce the weightand download time of your page and help your SEO. Take the following HTML for example...

    1. 2. 3. This is field number 14. 5. 6.

    7. This is an error message

    8. 9. 10.11. 12. This is field number 213. 14. 15.

    16. This is an error message

    17. 18.

    That's an example of how a form might be marked up, modified slightly for illustrative purposes. I'm sureyou'll agree it's pretty ugly and if you had a long form you'd end up with a fairly long ugly page. It's benicer if you could just put this in your HTML.

    1. This is field 1

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    15/19

    2. This is field 23. This is field 34. This is field 45. This is field 5

    All you have to do is a bit of jQuery manipulation to add all the ugly HTML back in. Like this...

    1. $(document).ready(function() {2. $('.field').before('');3. $('.field').after('4. 5. This is an error message');6. });

    It's not always advisable to do this, you'll get a bit of a flash as the page loads, but in certain situationswhere you've got a lot of repeated HTML it can really reduce your page weight and the SEO benefits ofreducing all your repeated extraneous markup should be obvious.

    17. Lazy load content for speed and SEO benefits

    Another way to speed up your page loads and neaten up the HTML that search spiders see is to lazy loadwhole chunks of it using an AJAX request after the rest of the page has loaded. The user can get browsingright away and spiders only see the content you want them to index.

    We've used this technique on our own site. Those purple buttons at the top of the page drop down 3 forms,directions and a google map, which was doubling the size of our pages. So, we just put all that HTML in astatic page and use the load() function to load it in once the DOM was ready. Like this...

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

    4. });

    I wouldn't use this everywhere. You have to consider the trade offs here. You're making extra requests to theserver and portions of your page might not be available to the user right away, but used correctly it can be agreat optimization technique.

  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    16/19

    18. Use jQuery's utility functions

    jQuery isn't just about flash effects. The creator has exposed some really useful methods which fill a fewgaps in JavaScript's repertoire.

    http://docs.jquery.com/Utilities

    In particular, browser support for certain common array functions is patchy (IE7 doesn't even have anindexOf() method!). Jquery has methods for iterating, filtering, cloning, merging and removing duplicatesfrom Arrays.

    Other common functions that are difficult in Javascript include getting the selected item in a drop down list.In plain old JavaScript you'd have to get the element using getElementByID, get the childelements as an array and iterate through them checking whether each one was selected or not. jQuerymakes it easy...

    1. $('#selectList').val();

    It's worth spending some time looking through the jQuery documentation on the main site and having anose around some of the lesser known functions.

    19. Use noconflict to rename the jquery object when

    using other frameworks

    Most javascript frameworks make use of the $ symbol as a shorthand and this can cause clashes whentrying to use more than one framework on the same page. Luckily there's a simple solution. The.noconflict() function gives control of the $ back and allows you to set your own variable name, like this...

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

    http://docs.jquery.com/Utilitieshttp://docs.jquery.com/Utilities
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    17/19

    20. How to tell when images have loaded

    This is another one of those problems that doesn't seem to be as well documented as it should be (not whenI went looking anyway) and it's a fairly common requirement when building photo galleries, carousels etc,but it's fairly easy.

    All you have to do is use the .load() method on an IMG element and put a callback function in it. Thefollowing example changes the "src" attribute of an image tag to load a new image and attaches a simpleload function.

    1. $('#myImage').attr('src', 'image.jpg').load(function() {2. alert('Image Loaded');3. });

    You should find that the alert is called as soon as the image is loaded.

    21. Always use the latest version

    jQuery is constantly improving and John Resig, it's creator, always seems to be in search of ways toimprove performance.

    jQuery is currently on version 1.2.6 but John has already revealed that he's working on a new selectorengine calledSizzle, which may apparently improve selector speeds in Firefox by up to 4x. So, it pays tokeep up to date.

    22. How to check if an element exists

    You don't need to check if an element exists on the page before you manipulate it because jQuery will willsimply do nothing if you try to select something and it isn't in the DOM. But when you do need to check ifanything has been selected, or how many items have been selected you can use the length property.

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

    http://ajaxian.com/archives/sizzle-john-resig-has-a-new-selector-enginehttp://ajaxian.com/archives/sizzle-john-resig-has-a-new-selector-enginehttp://ajaxian.com/archives/sizzle-john-resig-has-a-new-selector-engine
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    18/19

    3. }

    Simple, but not obvious.

    23. Add a JS class to your HTML attribute

    I learned this tip from Karl Swedberg whoseexcellentbooks I used to learn jQuery.

    He recently left a comment on one of my previous articles about this technique and the basics are asfollows...

    Firstly, as soon as jQuery has loaded you use it to add a "JS" class to your HTML tag.

    1. $('HTML').addClass('JS');

    Because that only happens when javascript is enabled you can use it to add CSS styles which only work ifthe user has JavaScript switched on, like this...

    1. .JS #myDiv{display:none;}

    So, what this means is that we can hide content when JavaScript is switched on and then use jQuery toshow it when necessary (e.g. by collapsing some panels and expanding them when the user clicks on them),while those with JavaScript off (and search engine spiders) see all of the content as it's not hidden. I'll beusing this one a lot in the future.

    To read his full article click here.

    24. Return 'false' to prevent default behaviour

    This should be an obvious one but maybe not. if you have a habit of doing this...

    1. Click me!

    http://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&s=books&qid=1229284831&sr=8-1http://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&s=books&qid=1229284831&sr=8-1http://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&s=books&qid=1229284831&sr=8-1http://www.amazon.co.uk/JQuery-Reference-Guide-Karl-Swedberg/dp/1847193811/ref=sr_1_3?ie=UTF8&s=books&qid=1229284831&sr=8-3http://www.learningjquery.com/2008/10/1-awesome-way-to-avoid-the-not-so-excellent-flash-of-amazing-unstyled-contenthttp://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&s=books&qid=1229284831&sr=8-1http://www.amazon.co.uk/JQuery-Reference-Guide-Karl-Swedberg/dp/1847193811/ref=sr_1_3?ie=UTF8&s=books&qid=1229284831&sr=8-3http://www.learningjquery.com/2008/10/1-awesome-way-to-avoid-the-not-so-excellent-flash-of-amazing-unstyled-content
  • 8/14/2019 25 Ways To Build Better jQuery Web Applications

    19/19

    ... and then attaching an event handler like this...

    1. $('popup').click(function(){2. // Launch popup code

    3. });

    ... it'll probably work fine until you use it on a long page, at which point you'll notice that the # is causing itto jump to the top of the page when your click event is triggered.

    All you have to do to prevent this default behaviour, or indeed any default behaviour on any event handleris to add "return false;" to your handler, like this...

    1. $('popup').click(function(){2. // Launch popup code

    3. returnfalse;4. });

    25. Shorthand for the ready event

    A small tip this one but you can save a few characters by using shorthand for the $(document).readyfunction.

    Instead of this...

    1. $(document).ready(function (){2. // your code3. });

    You can do this...

    1. $(function (){2. // your code3. });