如何在js文件中动态加载另一个js文件

JavaScript09

如何在js文件中动态加载另一个js文件,第1张

用document.write方法来实现。

在js文件中动态加载另一个js文件代码及注释步骤:

<html>

<body>

<script type="text/javascript">

document.write("<script src='要引用js'><\/script>")

</script>

<p>write方法的使用</p>

</body>

</html>

定义和用法

write() 方法可向文档写入 HTML 表达式或 JavaScript 代码。

语法

document.write(exp1,exp2,exp3,....)

1、直接document.write\x0d\x0a\x0d\x0adocument.write("")\x0d\x0a\x0d\x0a\x0d\x0a2、动态改变已有script的src属性\x0d\x0a

如果需要用原生js动态的加载另外一个js文件,可以使用原生js的document.createElement方法创建script节点,然后更改该节点的type和src属性,最后通过appendChild方法将该节点动态添加到html中,这样就可以了,参考代码如下:

var new_element = document.createElement("script")//创建新的script节点new_element.setAttribute("type", "text/javascript")new_element.setAttribute("src", "../js/jquery.js")document.body.appendChild(new_element)//添加到body节点的末尾

上例中是在body的最末尾添加的,当然同样可以在head中添加引用该js的标签:document.head.appendChild(new_element)