Reputation: 5052
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
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
Reputation: 68626
You should:
example();
example() { }
(document).ready()
Upvotes: 1
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