0

If I want to load another javascript file from a javascript file (ex. when I complete a level in a game), how would I do this?

(I'll add what I've tried in a minute)

DUUUDE123
  • 166
  • 1
  • 10

1 Answers1

0

Try this function:

var getScript = function(filePath, loadedCallback) {
    var head = document.getElementsByTagName('head')[0],
        jsFileScriptTag = document.createElement('script');

    jsFileScriptTag.type = 'text/javascript';
    jsFileScriptTag.src = filePath;
    jsFileScriptTag.onreadystatechange = loadedCallback;
    jsFileScriptTag.onload = loadedCallback;
    head.appendChild(jsFileScriptTag);
};

//ussage
getScript('/js/myFile.js', function() {
    //do something when the script has loaded.
});
taxicala
  • 21,408
  • 7
  • 37
  • 66
  • Thanks for your input! I came across another way, which is to use web workers. Have you ever tried that method out? – DUUUDE123 Nov 28 '15 at 22:28