Dzhuneyt
Dzhuneyt

Reputation: 8701

Two $(document).ready Events, jQuery Library Included Between the Two, Only the Second One Executes

I have the following structure (simplified):

// In <head>
$(document).ready(function(){
  // first event
});

// Near the end of <body>
// jQuery library is included at this point
$(document).ready(function(){
  // second event
});

And the browsers give me an error that the $ object is not defined during the first event. I've tried replacing it with the jQuery word, but then it says that jQuery is not defined.

I realize that the first event is called before the jQuery library is loaded, but I though this was the point of document.ready - to call it from anywhere as long as it's on the same page as the jQuery library.

Upvotes: 0

Views: 66

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382404

The point of $(document).ready( is to wait for the DOM to be ready, so that you can query the DOM elements. It needs jQuery, so the first line can't be interpreted if you don't have it loaded.

What you might do, if you really want your first code to be before jQuery import, is this :

window.addEventListener('load', function(){
     // here you can use jQuery (and the DOM too)
});

But I fail to see a reason to not simply move your code after jQuery import.

Upvotes: 3

Related Questions