1

I've come across similar questions but I think I have a small variation on this: I have a list of files I want to be able to load but some are dependent on eachother so the order in which they load - or actually parsed and executed - matters.

Simplified code of what I have now:

function loadscripts() {
    for (var i=0; i<list.length; i++) {
        var scriptElem = document.createElement("script");
        scriptElem.src = list[i];
        $("body").append(scriptElem);
}

var list ["script1.js","script2.js"];

loadscripts();

I assumed that, because I'm basically adding tags to the DOM, the browser will parse them in order like it does when they would be there in the 'static' html file. But it turns out it doesn't.

For example, I load hammerjs and its jquery hammer plugin. These are separate files so I add them to the dom in order but the jquery hammer plugin will sometimes throw an error (Hammer is undefined) when it is parsed before hammerjs.

So something like this is not safe to use:

// script1.js
var someObject = {
    value1:1, value2:2
}

// script2.js
console.log(someObject.value1);

This will (sometimes!) throw an error, something like "can not access 'value1' of undefined".

I could, like the similar questions and their answers here on SO point out, use script.onload but since I have multiple files I want to load that would require to keep track of which file is loaded, call the loadScript function again and add the next, and so on.. That would be a bit of a mess.

Does anyone know a solution that would work that is as clean as possible?

Related questions:

Community
  • 1
  • 1
REJH
  • 3,273
  • 5
  • 31
  • 56
  • 3
    Personally, i would leave it to libraries like `requirejs` to do the job for me. – Sandeep Nayak May 16 '16 at 05:34
  • See http://stackoverflow.com/questions/26124199/run-custom-code-after-jquery-has-been-loaded-via-modernizr/ – guest271314 May 16 '16 at 05:55
  • @guest271314 if I read the code correctly he is using a timeout to check if the script is loaded and retries if not..? That doesn't look like good practice..? – REJH May 16 '16 at 06:01
  • @SandeepNayak hmm I'd have to take a look at it. Thanks for now :)) – REJH May 16 '16 at 06:02

0 Answers0