Reputation: 7597
I understand jQuery, I just wanna ask, whats the difference between those 2 code examples (I know, it will do the same, but I am curious, if there is something specific with second example.
EXAMPLE 1:
$(document).ready(function() {
// some code #1
// some code #2
// some code #3
});
Here is all JS at one place.
EXAMPLE 2:
$(document).ready(function() {
// some code #1
});
$(document).ready(function() {
// some code #2
});
$(document).ready(function() {
// some code #3
});
Those functions (DOM ready) are placed in different JS files.
I am just thinking, how it will be processed, but I guess it will be executed after DOM is loaded and then in the order, how it is called in HTML.
Upvotes: 2
Views: 82
Reputation: 38345
Each separate function passed to $(document).ready()
will create its own scope for variables and functions, which can result in a pretty substantial difference. Take these two examples:
$(document).ready(function() {
function viewEvent(event) {
console.log(event);
return false;
}
$('a').on('click', viewEvent);
// works fine, clicking on an <a> element will log the event object
});
Then:
$(document).ready(function() {
function viewEvent(event) {
console.log(event);
return false;
}
});
$(document).ready(function() {
$('a').on('click', viewEvent);
// won't work, viewEvent is out of scope here
});
Upvotes: 5
Reputation: 6965
You can have as many of them as you wish, and they will be executed in the order that the $()
or $(document).ready()
functions are executed. (i.e. each handler is added to the queue).
Upvotes: 3
Reputation: 103348
I guess it will be executed after DOM is loaded and then in the order, how it is called in HTML.
That's correct.
These functions will be stacked and called linear in the order they are attached to the DOM ready event.
Upvotes: 2
Reputation: 150040
Multiple document ready handlers will all be called in the order they are bound. In general I would recommend just having the one to keep things tidy, except...
"Those functions (DOM ready) are places in different JS files."
That is the best reason I can think of for having multiple ready handlers.
"I am just thinking, how it will be processed, but I guess it will be executed after DOM is loaded and then in the order, how it is called in HTML."
That is correct.
Upvotes: 3