I am trying to dynamically load a JavaScript file by adding a script element to the head element, after which I test for the presence of a function defined inside that file to check that the load succeeded.
If I use this code:
var scriptElem = document.createElement("script");
scriptElem.type = "text/javascript";
scriptElem.src = 'myfile.js';
document.getElementsByTagName('head')[0].appendChild(scriptElem);
the new function isn’t defined afterwards. However, if I alter the last line to use jQuery, like so:
$('head').append($(scriptElem));
it is. As another clue, in the first case Firebug shows the new script element in the HTML tab, whereas in the second case it doesn’t.
I have tried using jQuery.getScript() to do this, but that didn’t work either. Also, if it’s relevant, the call is being made from a function supplied to jQuery via:
$(document).ready();
Can someone please explain what’s going on?
It looks like jQuery might be giving you a bit of help. From my hacking, $(‘head’).append(scriptElem); does append the script, but it doesn’t parse it immediately. So if you put a function inside called “function something(){};” then it’s defined on the following line using the JQuery append() method, but not using the native appendChild. (That’s as you’ve described.) However, if you put setTimeout(function(){alert(something)},1); then it is defined. It looks as if JQuery is managing to append the script tag but also force the browser to parse it immediately.
The key seems to be in the domManip function of the JQuery source code which contains the line:
which then goes to this:
So JQuery treats script tag appends as a special case, and some other JQuery magic goes and evaluates them synchronously, hence your function is available immediately.