如何在JS文件中引用另一个JS文件

通常如果一个页面JS代码太多,首先肯定会想到像 CSS 一样 单独写一个文件,然后引用到HTML页面中。如果我们又需要再JS代码中引用另一个JS文件,那我们应该怎么做呢?今早做项目遇到了这个问题,所以总结了一点答案(以JQuery 为例)

第一种方法:

1.html 文件代码:

<body>
    <input type="button" name="" id="bt" value="click">
</body>

1.js 文件代码

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "./jquery/jquery.js";  // jquery路径
document.getElementsByTagName('head')[0].appendChild(script);
setTimeout(function(){
    $(document).ready(function(){
        $("#bt").click(function(){
            alert("hello")
        })
    })
},100)

第二种:直接document.write

document.write(" < script language = javascript src = './jquery/jquery.js' >< / script>");

第三种 :(body标签存在得情况下)

var newScript = document.createElement("script");
newScript.setAttribute("type","text/javascript");
newScript.setAttribute("src","./jquery/jquery.js");
document.body.appendChild(newScript);
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐