如何推迟多个js脚本

时间:2016-07-14 07:08:14

标签: javascript

这很好用,但我想添加多个.js文件。如何为此添加多个来源?

 <script type="text/javascript">
function downloadJSAtOnload() {
 var element = document.createElement("script");
 element.src = "yourdeferscripts.js";
 document.body.appendChild(element);
 }
 if (window.addEventListener)
 window.addEventListener("load", downloadJSAtOnload, false);
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;
</script>

2 个答案:

答案 0 :(得分:0)

你可以做这样的事情(未经测试)

创建一个相关文件名的数组,现在循环遍历它并将其附加到正文

var _scripts = ["yourdeferscripts.js",'abc.js']; // array of js files name
<script type="text/javascript">
function downloadJSAtOnload() {
// Use array forEach to loop through it and append to the body
_scripts.forEach(function(item){ // 
 var element = document.createElement("script");
 element.src = item;
 document.body.appendChild(element);
 })
 }
 if (window.addEventListener)
 window.addEventListener("load", downloadJSAtOnload, false);
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;
</script>

答案 1 :(得分:0)

可能你正在寻找这样的东西?

备选方案#1

最简单的方法是使用数组:

&#13;
&#13;
// Array of the .js file names
var script_list = ["yourdeferscripts.js", 'anotherdeferscripts.js']; 
function downloadJSAtOnload() {
  // Runing through the array and appending to the body
  script_list.forEach(function(file) { // 
    var element = document.createElement("script");
    alert("This is " + file + " file.");
    element.src = file;
    document.body.appendChild(element);
  })
}
if (window.addEventListener)
  window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
  window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
&#13;
<body>
</body>
&#13;
&#13;
&#13;

备选方案#2

这使用onload函数加载一个单独的脚本。

&#13;
&#13;
function func1() {
  downloadJSAtOnload()
}

function func2() {
  downloadJSAtOnload2()
}

function downloadJSAtOnload() {
  alert("This is the first.");
  var element = document.createElement("script");
  element.src = "yourdeferscripts.js";
  document.body.appendChild(element);
}

function downloadJSAtOnload2() {
  alert("This is the second.");
  var element = document.createElement("script");
  element.src = "yourdeferscripts.js";
  document.body.appendChild(element);
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(func1);
addLoadEvent(func2);
addLoadEvent(function() {
  document.body.style.backgroundColor = '#EFDF95';
})
&#13;
<body>
</body>
&#13;
&#13;
&#13;