I have an application that is using ajax calls for loading the content. Those ajax calls are retrieving just the HTML. JavaScript is in another file.
After doing the AJAX-call I will call to a function that should start executing the JavaScript as soon as possible.
Here I leave a small function that will retrieve some code from an ajax call:
function loadPage(page) {
$(".container").html("");
if(page == "page1") {
$.ajax({
url: "/page1.php",
success: function(html){
$(".container").html(html);
loadPage1Script();
}
});
}else if(page == "page2"){
$.ajax({
url: "/page2.php",
success: function(html){
$(".container").html(html);
loadPage2Script();
}
});
}
}
After that, they will execute loadPage1Script() or loadPage2Script().
function loadPage1Script(){
//Start the carousel plugin, for example
}
A new code has been added to the HTML structure. Should I call to $(document).ready(); in the loadPage1Script() before executing the code to to attach all event handlers? Is there any differences if I do not do that? Will the script start faster if I add the $(document).ready(); ?
function loadPage1Script(){
$(document).ready(function(){
//Start the carousel plugin, for example
});
}
Taken from jQuery site(http://api.jquery.com/ready/):
"In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code."
If you are calling the
loadpagefunction after you have aleady calledThen it shouldn’t matter. Also, since the
$.fn.htmlfunction isn’t asynchronous, you will have no problem in running yourloadPageScriptfunctions straight away