我有2个JS文件.我如何使第二个JS文件只运行*后*第一个JS文件已经完成加载


I have 2 JS files. How do I make the 2nd JS file only run *after* the 1st JS file has finished loading?

我有两个JS文件。我如何使第二个JS文件只运行第一个JS文件已经完成加载?有没有办法显式地设置它?

基于这个答案,我如何动态加载一个javascript文件?

可以从第一个文件动态加载第二个文件。这样你就可以确保第一个文件是完全加载的。

  // 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);

假设你有两个js

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

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

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


1. js:

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

2. js:

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