Beachhouse
Beachhouse

Reputation: 5052

Load jQuery after DOM, how can I make $.ready() available to my page before jQuery is loaded?

I want to late load jQuery, but I have a small amount of inline javascript the runs on $.ready(). Since jQuery isn't loaded, these lines throw an error and never run. Is there a way I can make $.ready() an available function, but wait on execution until jQuery is loaded?

Thanks!

Upvotes: 3

Views: 872

Answers (3)

jfriend00
jfriend00

Reputation: 708016

One option for a generic way to solve this is to put your inline javascript in a function and add that function to a globally accessible array - don't call it yet. These are essentially functions that you want to schedule for document.ready() when document.ready is available.

Then, when you do load jQuery, you set up a document.ready() handler that cycles through all the functions in that array and calls them.

// declare global at the top of your web page
var readyFns = [];

// in your inline code, add a function to the readyFns array
readyFns.push(myInlineFn);

// when your jQuery code loads, do this:
$(document).ready(function() {
    for (var i = 0; i < readyFns.length; i++) {
        readyFns[i]();
    }
});

If you want to use anonymous functions, you can do the middle step like this:

// in your inline code, add a function to the readyFns array
readyFns.push(function() {
   // put your code here
});

Upvotes: 4

dsgriffin
dsgriffin

Reputation: 68626

You should:

  1. replace ready with a function call e.g. example();
  2. create a function e.g. example() { }
  3. put that function inside (document).ready()

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191799

Instead of using .ready, you could use the non-jQuery equivalent such as window.onload, but these tend to be somewhat incompatible with .ready, so I'm not sure if they will work for your needs.

Someone apparently has extracted jQuery's ready function so it can be used alone: http://code.google.com/p/domready/

Upvotes: 1

Related Questions