I do a simple check if js file exists. If not, I try to load it dynamically before other scripts from bottom of a page are loaded. Is it possible to do? Here is fiddle where bottom script is executed before thus giving errors. https://jsfiddle.net/vnfxus56/1/
thank you.
<div id="top">top</div> <script> doesFileExist('https://ajax.googleapis.com/ajax/libs/nonexistingfile.js'); function doesFileExist(urlToFile) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', urlToFile, false); xhr.send(); if (xhr.status == "404") { console.log("File doesn't exist"); var script = document.createElement('script') script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js' document.head.append(script) return false; } else { console.log("File exists"); return true; } } </script> <script> //this is printed out of a variable as a bunch of inline jquery code $("#top").fadeOut(); </script>
$isn't defined. You could make this work, but you should change your code so it waits until everything finished loading before executing the page's script.onloadevent of thescriptelements is a good option.