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?