3

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!

Beachhouse
  • 4,972
  • 3
  • 25
  • 39

3 Answers3

4

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
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

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/

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • +1 domready could be what I'm looking for, but the code looks like there's a bit of overhead in there to do this. – Beachhouse Dec 05 '12 at 19:29
1

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()
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
  • Very very simple answer, but I need to check as to how this would work. I have more than one ready block that loads before the DOM, I think this would limit me to one usage. – Beachhouse Dec 05 '12 at 19:31