In my app I use Ajax navigation with jQuery post.
Scenario:
Lets suppose a user types the url and loads the index page. Now he wants to go to his profile page(suppose he is already logged in previously). Clicking at "My profile" link, a jQuery post is executed and it returns the html result in the main div.
The problem i have:
The profile page, has its own profile_functions.js file which contains the profile related js functions.At the jQuery post, i do checks, so when the user profile page is requested then it loads the profile_functions.js before doing the jQuery post. (appends it using document.getElementsByTagName("head")[0].appendChild(file);
)
Inside the profile_functions.js i have some jQuery plugins which need to initialize using $(document).ready(function(){ });
which is placed at the HTML result. The problem i have noticed is that sometimes the jQuery post result is retrieved earlier than the load of the .js file has been completed, so i get an error and of course the jQuery plugin doesn't work.
So my question is: Using jQuery post, what is the best and successful way to load the new .js file which is required from the post result-html code?
EDIT: As requested, here is the code I have:
//Loads the new JS
function loadjscss(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (typeof fileref!="undefined"){document.getElementsByTagName("head")[0].appendChild(fileref);}
}
//Part of function that loads the new page
function ajax_menu_nav(requested_page) {
if(requested_page=='profile_page'){
loadjscss("/static/profile_functions.js", "js");
}
$.post("/ajax_menu.php",
{
rp:requested_page,
rand:Math.random()
} ,
function(rd) {
$('#main').html(rd.tpl);
}, "json"
);
}
Now the result HTML code contains among the others:
$(document).ready(function(){ function_a(); });
Which the function_a() is from profile_functions.js file.
I think the problem is that function_a is called when DOM is ready and therefore before script is loaded. You should call it by yourself when script is loaded, in a callback.