I’m trying to dynamically load an external .js file (according to an input I get from the user).
Currently my code looks like this:
function createScript(src, id) {
if (document.getElementById(id) == null) {
var newScript = document.createElement('script');
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", src);
newScript.setAttribute("id", id);
document.getElementsByTagName("head")[0].appendChild(newScript);
}
}
This kind of work. It does load the script, but if I try to call a function that is defined inside the new script it won’t work. The weird thing is if I wait for a second (using an alert("test") or something like that) the script does work.
I guess its because the browser adds the <script> tag immediately, but it takes it a little longer to “read” the script inside of the .js file.
I tried playing with "typeof testfunction === 'function'" with a few variations but no luck.
Any good way of doing this?
February 21, 2017 – how jQuery does it
jQuery.getScriptis now just a wrapper forjQuery.getjQuery.getis just a wrapper ofjQuery.ajax– it is defined using metaprogramming as …jQuery.ajaxis this 430+ LOC monsterSo yeah, this is obviously ridiculous to try to remove all the dependencies from this code. You’re better off just including jQuery if you want to use jQuery’s method for loading external scripts asynchronously.
Or, consider using a different tool altogether.
July 16, 2013 – from jQuery guts with no dependencies [source code citation needed]