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?