1

I have 2 JS files. How do I make the 2nd JS file only run after the 1st JS file has finished loading? Is there a way to explicitly set this?

m0a
  • 1,005
  • 2
  • 15
  • 29

2 Answers2

3

Based on this answer How do I load a javascript file dynamically?

You can load the second file dynamically from the first one. This way you can be sure the first one is completely loaded.

  // DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
Community
  • 1
  • 1
2

Given that you have two js

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

2.js

document.getElementById("btn").onclick = function(){
    fn1();
}

1.js

function fn1(){
 alert("external fn clicked");
}

OR


1.js:

function fn(){
   alert("Hello! HAPPY CODING");
}

2.js:

$.getscript("1.js",function(){
fn();
});

Hope This Helps...

J Kenneth
  • 96
  • 4