如何在加载下一个之前等待加载一个javascript

时间:2018-03-03 09:06:07

标签: javascript

我想知道如何在加载下一个脚本之前等待加载一个脚本。例如(并且实际上还将另一页完全加载到页面中):

<html>
<script src = "script1"></script>

<script src = "script2"></script>

<script>
$(document).ready( function() {
    $("#content1").load("index2.html");
});
</script>
</html>

所以在正确加载script1之后(并在那里运行所有那些),我想加载脚本2,然后加载完成后,我想将文档index2.html加载到这个html文档中。

到目前为止,我一直在尝试的是这个但是它并不像我想的那样完全正常工作。

File1:scriptOrderTest.html

<html>

<div id ="content1"></div>

<script src="js/jquery-3.2.1.min.js"></script>
<script>
var variable1 = undefined;
$(document).ready( function() {
    $.ajax({
      url: "script1.js",
      dataType: "script",
      success: () => {
        $.ajax({
          url: "script2.js",
          dataType: "script",
          success: () =>{
            // do the stuff you need
            $("#content1").load("index2.html");
          }
         });
       }
       });       
});
</script>
</html>

File2:script1.js

console.log("Starting script 1");
function revealTime(){
    console.log("Oh, I just wasted 5 seconds of my life")   
}

//This script is just wasting time
setTimeout(revealTime,5000);

File3:script2.js

console.log("Starting script 2");
function revealTime(){
    console.log("Oh, I just wasted 5 seconds of my life AGAIN") ;
    variable1 = "Pizza";
}

//This script is just wasting time
setTimeout(revealTime,5000);

File4:index2.html

<html>
<script src="js/jquery-3.2.1.min.js"></script>

<script>
    document.write("The variable is:"+variable1);   
</script>
</html>

首先,目标是等待脚本完成,以便变量可以在将其写入页面之前获取值。上述代码不是这种情况。

1 个答案:

答案 0 :(得分:0)

您可以使用Promise和链操作一起解决此问题。

如果您创建了一个添加脚本的功能,然后在完成后告诉您。

类似的东西:

function addScript(url){
  return new Promise((resolve, reject) => {
    console.log("Download", url);
    var script = document.createElement("script")
    script.type = "text/javascript";
    script.onload = function(){
      console.log(`Download done (${url})`);
      resolve(1);
    };

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
  });
}

定义你需要的所有脚本,我只是用vue做了一个无用的例子。

const scripts = [
  "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js",
  "https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.1/vue-router.js"
];

顺序

您在问题中要求的内容 - 当时下载,延迟下载下一个脚本,直到第一个脚本完成。

const tasks = scripts[Symbol.iterator]();

function addAllScripts(callback){
  const url = tasks.next().value;
  if(url){
    addScript(url).then( () => { addAllScripts(callback); } );
  }else{
    callback();
  }
};
addAllScripts(() => {
  console.log("Ready");
  new Vue({
    el: '#app',
    template: '<p>hello world</p>'
  });
});

&#13;
&#13;
function addScript(url){
	return new Promise((resolve, reject) => {
  	console.log("Download", url);
  	var script = document.createElement("script")
    script.type = "text/javascript";
    script.onload = function(){
    	console.log(`Download done (${url})`);
      resolve(1);
    };

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
  });
}

const scripts = [
"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js",
"https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.1/vue-router.js"
];

const tasks = scripts[Symbol.iterator]();

function addAllScripts(callback){
  	const url = tasks.next().value;
    if(url){
      addScript(url).then( () => { addAllScripts(callback); } );
    }else{
      callback();
    }
};
addAllScripts(() => {
	console.log("Ready");
          new Vue({
            el: '#app',
            template: '<p>hello world</p>'
          });
});
&#13;
<div id="app"></div>
&#13;
&#13;
&#13;

<强>并行

最佳解决方案,更快的执行 - 一次添加所有脚本,并等待所有脚本完成

const tasks = scripts.map(addScript);

Promise.all( tasks )
       .then(function(){
          console.log("Ready");
          new Vue({
            el: '#app',
            template: '<p>hello world</p>'
          });
       }); 

&#13;
&#13;
function addScript(url){
	return new Promise((resolve, reject) => {
  	console.log("Download", url);
  	var script = document.createElement("script")
    script.type = "text/javascript";
    script.onload = function(){
    	console.log(`Download done (${url})`);
      resolve(1);
    };

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
  });
}

const scripts = [
"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js",
"https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.1/vue-router.js"
];

const tasks = scripts.map(addScript);

Promise.all( tasks )
       .then(function(){
          console.log("Ready");
          new Vue({
            el: '#app',
            template: '<p>hello world</p>'
          });
				}); 
&#13;
<div id="app"></div>
&#13;
&#13;
&#13;