i have a function the loads JS files, one of the JS file is important to the other code to run successfully so i am trying to wait till the function successfully load it.
Till now i have tried several ways- but they didn't work for me, like this one for example:
$(document).ready(function () { function kickOff() { return new Promise(function (resolve, reject) { loadRemoteFile("hconfig.js"); }); } kickoff().then(function (result) { run the code that depends on the code that kickoff() run }); }); LoadRemoteFile function
function loadRemoteFile(filename, loadIntoHeader){ filetype = filename.match(".css") ? "css" : "js"; if (filetype=="js"){ //if filename is a external JavaScript file if(!loadIntoHeader){ var script = document.createElement("script"); script.type = "text/javascript"; script.src = filename; document.body.appendChild(script); }else{ var fileref=document.createElement('script'); fileref.setAttribute("type","text/javascript"); fileref.setAttribute("src", filename); document.getElementsByTagName("head")[0].appendChild(fileref); } }else if (filetype=="css"){ if(!loadIntoHeader){ var style = document.createElement("link"); style.type = "text/css"; style.rel = "stylesheet"; style.href = filename; document.body.appendChild(style); }else{ var fileref=document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", filename); document.getElementsByTagName("head")[0].appendChild(fileref); } } } Is it a good solution? why isn't it working?
Promise()you create. Only after that happens willthen()be executed. To do this you'll most likely need to add a callback toloadRemoteFile()loadRemoteFiledoing? That is your own implementation... in general you can do something like this:jQuery.getScript("hconfig.js", function() { /* your other code */ })"loadRemoteFile"