You can create your <script>
element with an “onload” handler, and that will be called when the script has been loaded and evaluated by the browser.
var script = document.createElement('script');
script.onload = function() {
alert("Script loaded and ready");
};
script.src = "http://whatever.com/the/script.js";
document.getElementsByTagName('head')[0].appendChild(script);
You can’t do it synchronously.
edit — it’s been pointed out that, true to form, IE doesn’t fire a “load” event on <script>
tags being loaded/evaluated. Thus I suppose the next thing to do would be to fetch the script with an XMLHttpRequest and then eval()
it yourself. (Or, I suppose, stuff the text into a <script>
tag you add; the execution environment of eval()
is affected by the local scope, so it won’t necessarily do what you want it to do.)
edit — As of early 2013, I’d strongly advise looking into a more robust script loading tool like Requirejs. There are a lot of special cases to worry about. For really simple situations, there’s yepnope, which is now built into Modernizr.