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?
Asked
Active
Viewed 63 times
2 Answers
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

Javier Suero Santos
- 544
- 7
- 21
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