4

Recently discovered the head.js library and boy am I happy with it, although I'm still a bit confused about one thing.

From headjs.com:

The “DOM ready” event such as $(document).ready() is already fired when the scripts arrive. If the loaded scripts depend on that event make sure your library can handle this. jQuery 1.4+ works.

With this in mind, what is the best way to set up a page that uses jQuery if the code within $(document).ready() depend of the external scripts loaded with head.js?

Can we just lose the $(document).ready() call all together and still successfully set up things like event listeners which rely on the the document being ready? Ex:

head.js("script1.js", "script2.js", "script3.js", function() {
    $('#button').click(function(event) {
        alert("clicked");
    });
});

Or do we want to wrap $(document).ready() within the function?

Just wondering what the best practice is to ensure that everything is ready to go by the time it needs to be.

dougmacklin
  • 2,560
  • 10
  • 42
  • 69

1 Answers1

4

Either way is fine. Handlers passed to ready() are called immediately if the DOM is already fully initialized.

For a small performance gain, you may want to remove the ready handler and include your code directly, unless you're relying on a side effect like jQuery's $ object being passed to the handler.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • so then head.ready() waits to execute after the DOM is ready like $(document).ready(), or does it just execute after the scripts are loaded? – dougmacklin Aug 31 '12 at 19:29
  • 1
    @Dougie, as the docs you quoted say, `the “DOM ready” event such as $(document).ready() is already fired when the scripts arrive`. So `head.js()` behaves exactly like `ready()` in this context. (I suspect `head.js()` waits for the DOM to be ready before injecting the scripts.) – Frédéric Hamidi Aug 31 '12 at 19:32