在主体中的脚本执行之前加载外部js文件(无jQuery)

时间:2019-06-15 19:54:13

标签: javascript

我有一个网站,该网站应首先加载外部js代码,然后再在dom中执行代码,但我将无法工作。每当我的外部代码在body标签中的js之后加载时,会导致诸如未定义的类和变量之类的问题

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Site</title>
    <link rel="stylesheet" href="./style.css">
    <script src="./project/load.js"></script>
</head>
<body>
    <h1>project</h1>
    <div id="project"></div>
    <script src="./script.js"></script>
</body>
</html>

./ project / load.js

window.onload = function() {
    var links = ["./project/script1.js", "./project/script2.js", "./project/script3.js"];
    for(var link of links) {
        var script = document.createElement("script");
        script.src = link + "?0";
        script.setAttribute("onerror", "reload(this)");
        document.head.append(script);
    }
}

我也尝试了'addEventListener('DOMContentLoaded',function(){...});'但它也确实有效。

希望你能帮助我。

编辑1: 请求订单

./ project / load.js

./ script.js

./ project / script1.js

./ project / script2.js

./ project / script3.js

2 个答案:

答案 0 :(得分:1)

使用defer属性加载您的JavaScript。用下面的内容替换HTML。 “ defer”属性允许仅在页面加载完成后才运行javascript。表示DOM可用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Site</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <h1>project</h1>
    <div id="project"></div>
    <script src="./project/load.js" defer></script>
    <script src="./script.js" defer></script>
</body>
</html>

参考文献和进一步阅读

  1. https://www.sitepoint.com/introduction-jquery-deferred-objects/
  2. https://www.w3schools.com/tags/att_script_defer.asp

答案 1 :(得分:0)

这就是我所做的。请在下面看这个

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Site</title>

</head>
<body>
    <h1>project</h1>
    <div id="project"></div>
    <script src="load.js" defer></script>
    <script src="script.js" defer></script>
</body>
</html>

Javascript-load.js

(function(){
  var dom = document.getElementById("project");
  if( dom !== null ){
    dom.innerHTML =  "<p>Iam load.js " + new Date().toString() + "</p>";
    console.log("Iam load.js " + new Date().toString());
  }
})();

Javascript-script.js

(function(){
  var dom = document.getElementById("project");
  if( dom !== null ){
    dom.innerHTML = dom.innerHTML + "<p>Iam script.js " + new Date().toString() + "</p>";

    console.log("Iam script.js " + new Date().toString());
  }
})();

输出

enter image description here

您可以看到我添加脚本的顺序首先加载。