Marti Markov
Marti Markov

Reputation: 766

Load jQuery at the end of the page?

I have some code that uses jQuery and it's in the html. I include jQuery at the bottom of the page so the problem is that every use of $. is undefined.

I remember reading somewhere that you can create a holder $ function and when the jQuery get loaded it will execute everything that called $. (like some sort of a stack).

Can you please tell me how to do this? Like with a code example or if you have that article link it will be great. :)

Upvotes: 0

Views: 1886

Answers (2)

Gadde
Gadde

Reputation: 1471

Make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.

It could be that you have your script tag called before the jquery script is called place the jquery.js before your script tag and it will work

Upvotes: 1

jfriend00
jfriend00

Reputation: 707486

No, you can't make a whole bunch of jQuery calls before it's loaded and then expect something later on to play back everything.

Your choices are:

  1. Load jQuery before things that use it.
  2. Don't use any jQuery calls until after the page and jQuery are loaded.
  3. Create your own list of initialization functions that you want called after jQuery is loaded and register those callbacks as the page is loading. Then, have your own function that walks that list of initialization functions and calls them all once jQuery is loaded to kick of the initialization that uses jQuery.

But, #3 seems like a lot of work that isn't really necessary. Either load jQuery up front or don't run your initialization functions that use jQuery until after it is loaded - either is cleaner and simpler.

Keep in mind that you also need to load any jQuery plugins after jQuery is loaded because they use jQuery to initialize/install themselves.

Upvotes: 2

Related Questions