03 July 2009

Start your javascript with jQuery's document ready

jQuery has a nice feature. When a browser loads a page, the elements aren't available to the page until it's been loaded by the browser. This means that when you run a javascript script, it won't execute if the element isn't already loaded.

A way to ensure that everything has loaded is to use the onload attribute on the body tag. The problem with this is that it has to wait until it has loaded all the images and everything else as well, which means no script will execute until everything is loaded — which takes too long.

But John Resig has come up with a very nice feature:

    // your code here

This is an excellent little bugger to use, as it waits until the document elements are loaded, and then executes. It doesn't wait for all the images to load. This means your code will execute much faster!

A short way of coding it is:

$(function() {
    // your code here

I normally attach a javascript file to my document the same way I attach my jQuery library file, and thus I don't need any script tags in my layout template.

Take care

No comments:

Post a Comment