1

I have 5 different js files which I want to execute after an ajax call success response status.

What I am currently doing is :

function require(list, fn)
{
    for (var i = 0; i < list.length; i++) {
        var headID = document.getElementsByTagName("head")[0];
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.src = list[i];
        if (newScript.readyState){  //IE
        newScript.onreadystatechange = function(){
            if (newScript.readyState == "loaded" ||
                newScript.readyState == "complete"){
                newScript.onreadystatechange = null;
                callback();
            }
          };
        } else {  //Others
          newScript.onload = function(){
            callback();
        };
      }

      newScript.src = url;
      headID.appendChild(newScript);
    }
}

Let's say I have file1.js,file2.js,file3.js . I have a variable dca declared on file2.js which I want to use for some operations in file3.js. For that I need to load file1.js,file2.js sequentially . But unfortunately, this is not happening in the method that I am using.

Please help how to achieve this goal.

I even tried with

addEventListeners('load',function({ //some operations }));

but to no effect.

3
  • you can define it in <head><script> var dca;</script></head> Commented Oct 25, 2015 at 14:14
  • if you need them all to load first use promises or a loader like require.js Commented Oct 25, 2015 at 14:24
  • "have a variable dca declared on file2.js" Is dca a global variable ? Commented Oct 25, 2015 at 14:27

1 Answer 1

0

This should work:

const require = ([head, ...tail]) => {
  const loadScript = link => new Promise((fulfill, reject) => {
    const script = document.createElement('script');
    script.addEventListener('load', fulfill);
    script.addEventListener('error', reject);
    script.src = link;
    document.head.appendChild(script);
  });
  loadScript(head).then(() => {
    if (tail.length > 0) {
      require(tail);
    }
  });
};

I hope that code is self-explaining.

Also make sure that dca variable is global.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.