如何在一个js中引用多个js文件

JavaScript012

如何在一个js中引用多个js文件,第1张

可以创建一个函数叫require 该函数支持两个参数

第一个参数 src  需要引入的script的路径 (这个参数可以是路径也可以是一个数组 多个js文件)

第二个回掉函数 在引入的script标签加载完成了调用

因为楼主是引用js文件所以必须要在引入的js加载完成了才能运行后面的js

所以下面给出一份演示

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title>e演示</title>

    <script type="text/javascript">

    function require(src,fun){

     function centerFun(O){

     var num=0

     for(var i=0i<O.lengthi++){

     (function(j){

if(O[j].complate){

     num++

     if(num==O.length){

     if(fun){

     fun()

     }

     }

     }else{

     O[j].onload=function(){

     num++

     if(num==O.length){

     if(fun){

     fun()

     }

     }

     }

     }

     })(i)

     }

     }

     if(typeof src=="object"){

     var d=new Array

     for(var i=0i<src.lengthi++){

     var e=document.createElement("script")

     document.body.appendChild(e)

     e.setAttribute("src",src[i])

     d.push(e)

     }

     centerFun(d)

     return 0

     }

     if(typeof src=="string"){

     var script=document.createElement("script")

     script.setAttribute("src",src)

     document.body.appendChild(script)

     if(script.complate){

     if(fun){

     fun()

     }

     }else{

     if(fun){

     script.onload=function(){

     fun()

     script.onload=null

     }

     }

    

     }

     }

    }

    </script>

</head>

<body>

<script type="text/javascript">

require(["http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"],function(){

console.log($)

})

</script>

</body>

</html>

该演示定义了一个函数require

可以看到代码中并没有script标签 而是通过require引入的在加载完成过后我显示了一下$说明函数已经将script加载完成了

你的意思不是很理解

通常是在html文件中引入多个js文件。当然你需要路径写正确。

现在流行的打包工具比如webpack,是可以实现多个js,压缩成一个js文件。

同样的css文件也可以整合成一个。

不过这样做的前提是你需要明白中间编写的规则和注意事项

一般你应该尽量使用面向对象的方式写JS,这样可以避免声明全局变量,全局变量是造成冲突的最大问题。普通人要想两个function都能访问一个变量,那肯定是声明全局变量了,但如果你想两个function能访问同一个变量,而第三个function又不能访问这个变量怎么办,这就会用到prototype属性了,例如:Sample1 = function(){ this.a = 1}Sample1.prototype.method1 = function(){ this.a++alert(this.a)}Sample2 = function(){ this.a = 3}Sample2.prototype.method1 = function(){ this.a++alert(this.a)}这样两个a就不会冲突,而又可以在方法之间共享,我也是kiang来的