JQuery script loading gotcha

Posted by – January 20, 2010

Today, I was working on some javascript using JQuery 1.3.2 and the lightbox plugin Colorbox.

Whilst most things were working perfectly, one special case I had wasn’t playing well.  From the following code I was getting a number of errors:

  $.fn.colorbox({
    iframe: true,
    href: 'url.php',
    innerWidth: 250,
    innerHeight: 400
  });

This was returning the following under different test conditions:

  $overlay is undefined
  settings is undefined
  a is undefined

etc etc etc.

This was causing me to start pulling me hair out as nothing I was doing from following the documentation was working. After a while I noticed that the colorbox.js file was being included AFTER my application js file which contained the calls to colorbox.

‘No problem’ I thought, as it’s all wrapped up nicely in $(document).ready… at least, until I started doing some digging.

Over the past few years I’ve read that ready() returns when your page is ready to rock, which is not correct. ready() tells you when the DOM is ready to be manipulated. Unfortunately for us, loading JS files does not constitute part of this process. Therefore, my application code was trying to do stuff before my colorbox code had loaded properly.

This leads me to think that it would be really handy in jQuery to have some sort of complete() event, whereby it returns when the DOM is ready(), AND all of the required elements on the page have finished loading.

In future, I’ll definitely be more careful with calling JS code from external files.

1 Comment on JQuery script loading gotcha

Closed

  1. The event you’re looking for is called the window.onload event, so just use:

    $(window).load();

    instead of:

    $(document).ready();

    The window.onload will wait for all external sources to load (JS, CSS, images, etc) before firing.

    PS – You should also be able to resolve your issue if you just load the plug-in src before the script block containing your ready() code.