If you want to check If script is loaded or not, you can do it by adding script.onload=function(){...}
.
must note ‘- the script.onload
must come before script.src
Your code, with onload function
loadScriptFromUrl = function(url) {
var script = document.createElement('script');
script.type = 'text/javascript';
document.body.appendChild(script);
script.onload=()=>{
console.log("script loaded")
//whatever you want to do
}
script.async = false;
script.src = url;
script._url = url;
};
If you want to check for any error on loading you can go with script.onerror=function(){...}
It will also come before script.src
loadScriptFromUrl = function(url) {
var script = document.createElement('script');
script.type = 'text/javascript';
document.body.appendChild(script);
script.onerror=()=>{
console.log("script not loaded")
//reload script like below
loadScriptFromUrl(url);
//or reload the whole window by location.reload() method
}
script.async = false;
script.src = url;
script._url = url;
};
If you want to wait until the function loads the script you can put this function under an async function, add await keyword before it and return a promise resolve under script.onload();
E.g.
async function parentFunct(){
loadScriptFromUrl =await function(url) {
return new Promise((resolve,reject)=>{
var script = document.createElement('script');
script.type = 'text/javascript';
document.body.appendChild(script);
script.onload=()=>{
console.log("script loaded")
resolve();
}
script.async = false;
script.src = url;
script._url = url;
})
};
}
The above code will stop everything inside parentFunc() until the script is loaded Read more about js promises https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
CLICK HERE to find out more related problems solutions.