??旎陌l(fā)展史

世人皆醒,為我獨(dú)醉,人生何苦如此---sunnyhuang

題目1: 為什么要使用模塊化?

  1. 解決命名沖突
  2. 依賴管理
  3. 可以提高代碼的可讀性
  4. 提高代碼的復(fù)用性
  5. 避免污染全局變量

題目2:CMD、AMD、CommonJS 規(guī)范分別指什么?有哪些應(yīng)用

不同的運(yùn)用

gulp和webpack
gulp和webpack
  • AMD(異步模塊定義):由于瀏覽器加載腳本天生異步,AMD是一個(gè)在瀏覽器??旎_發(fā)的規(guī)范,但是由于元素的js并沒(méi)有define()和require(),所以AMD規(guī)范運(yùn)用了requirejs庫(kù)。

  • ** CMD(通用模板定義)**:也是異步加載模塊,它和AMD只是模塊定義的方式和模塊記載的時(shí)機(jī)不同

    AMD和CMD的區(qū)別以及運(yùn)用

    1. 都運(yùn)用于瀏覽器端,AMD是異步加載資源,而CMD是松散加載資源,根據(jù)需求加載。
    2. AMD是全部加載后,然后需求使用,而CMD是按需加載,就近依賴
    3. AMD在加載模塊完成后就會(huì)執(zhí)行模塊,所有??於加涊d完成后,就會(huì)進(jìn)入required的回調(diào)函數(shù),執(zhí)行主邏輯函數(shù),,這樣的效果就是依賴模塊的執(zhí)行順序和書寫順序不一定一致,看網(wǎng)絡(luò)速度,哪個(gè)先下載下來(lái),哪個(gè)先執(zhí)行,但是主邏輯一定在所有依賴加載完成后才執(zhí)行。
    4. CMD加載完某個(gè)依賴模塊后并不執(zhí)行,只是下載而已,在所有依賴模塊加載完成后進(jìn)入主邏輯,遇到require語(yǔ)句的時(shí)候才執(zhí)行對(duì)應(yīng)的模塊,這樣模塊的執(zhí)行順序和書寫順序是完全一致的
    //AMD
    define(['jquery','dailog','carousel'],function(jquery,dailog,Carousel){
      var $=jquery;
      var dailog=dailog;
      var Carousel=Carousel;
    })
    //CMD
    //1. 定義一個(gè)??靘yModule.js
    define(function(require,exports,module){
      var $=require(jquery);
      $("div").addClass("active");
      exports.add=function(){
        var i=0;
        i++
        return i
      }
    })
    define(function(require,exports,module){
      var sum=require("myModule").add;
      console.log(sum)
    })
    
  • CommonJS:是服務(wù)器端??斓囊?guī)范,Node.js就是運(yùn)用這個(gè)規(guī)范,使用與同步加載資源,一個(gè)單獨(dú)的文件就是一個(gè)模快,每一個(gè)??於加幸粋€(gè)單獨(dú)的作用域。

    1. 不需要引用其它的庫(kù),node.js自動(dòng)封裝了一個(gè)2個(gè)對(duì)象用于模快的輸出和請(qǐng)求
    2. module.exports ??斓奈ㄒ怀隹冢覀冃枰涯?煲敵龅臇|西放入該對(duì)象。
    3. require() 加載模塊使用require方法,該方法讀取一個(gè)文件并執(zhí)行,返回文件內(nèi)部的module.exports對(duì)象
    //定義一個(gè)a.js文件
    var name="hcc";
    function printName(){
      console.log(name)
    }
    module.exports={
      printName:printName
    }
    
    //在b.js中引用a.js
    var b= require('./a')  //接受a.js的exports的值 
    b.printName()    //輸出hcc
    

requirejs詳解

  1. 首頁(yè)加載require.js的文件

    <script data-main="scripts/main.js" src="scripts/require.js"></script>
    //首先瀏覽器不會(huì)識(shí)別data-main屬性的地址,
    

//當(dāng)require.js加載完成后,發(fā)現(xiàn)require.js里有data-main的內(nèi)容,
//就會(huì)回頭加載data-main里面的位置資源

2. require.config() 配置文件,配置資源的入口
![事例文件夾配置](http://upload-images.jianshu.io/upload_images/3635292-9976be7feae413a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

// 1.加載requirejs庫(kù)(假如下載后的require.js在lib下)
<script scr="js/lib/require.js"></script>
//2.直接在index.html下配置require.js的文件路徑
<script>
requirejs.config({
baseUrl: "js/lib",
paths:{
app: '../app',
}
})
//加載模快的入口
requirejs(['jquery','convas','app/sub'],function($,convas,sub){
........
})
</script>

- AMD規(guī)范的調(diào)用

//1. 沒(méi)有回調(diào)函數(shù),就會(huì)直接調(diào)用依賴
define([jquery])
//2. 有回調(diào)函數(shù),沒(méi)有依賴
//main.js
define(function(){
var add = function(x, y) {
return x + y;
};
return {
add: add
};
})
//3. 有依賴,需要指明依賴數(shù)組
define(['myMoudel','jquery'],function(mymoudel,$){
function foo(){
dosomething() .....
}
return {
foo:foo
}
})


### 項(xiàng)目實(shí)際運(yùn)用
![根目錄列表](http://upload-images.jianshu.io/upload_images/3635292-d63146917d5ced4b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
1. 首頁(yè)引入require.js
`<script data-main="./js/app/main.js"  src="./src/js/require.js"></script>`
**解析:**當(dāng)瀏覽器加載到require.js,加載完成后,會(huì)去尋找data-main里面的腳本運(yùn)用到頁(yè)面中
2. 當(dāng)解析完成后,會(huì)找到相應(yīng)路經(jīng)的main.js文件

requirejs.config({
baseUrl: './js/lib', //相對(duì)于根路徑而已(index.html)
paths: {
'app': '../app' //設(shè)置簡(jiǎn)寫的路徑
}
});
//加載模快入口
requirejs(['app/index']);
//配置文件main.js的baseUrl是相對(duì)于index.html而言
//配置完require.config后,需要加載???,
//對(duì)于沒(méi)有回調(diào)函數(shù),就會(huì)直接調(diào)用依賴,依賴位置在./js/lib/app/main.js

3. `./js/lib/app/main.js`里面的js文件加載頁(yè)面的主要功能

define(['jquery','goTop','Carousel','Waterfall'],function( $ ,GoTop,Carousel,Waterfall){
new GoTop($(".goTop")) //回到頂部

Carousel.init($(".carousel"))  //輪播
//
new Waterfall($(".wrap-pic"))  //瀑布流

})

**解析:** 由于我們已經(jīng)設(shè)置了main.js的基本目錄,后面所有加載的js文件都是根據(jù)baseUrl+paths的路經(jīng),所以./js/lib下面的js插件都可以直接運(yùn)用名字(后綴名js省略)
> 相當(dāng)于加載jquery.js / goTop.js / Carousel.js / Waterfall.js  并給它傳入到相應(yīng)的回調(diào)函數(shù)的形參,用來(lái)調(diào)用相應(yīng)的方法。

4. 解析define的用法
為什么`define(['jquery','goTop','Carousel','Waterfall'],function(){.....}`之后就會(huì)有相應(yīng)的方法和函數(shù)出來(lái)呢?

define('id',[],function(){})
id: ??烀郑o一個(gè)js文件取一個(gè)名字
[] : ??煲蕾嚕褪悄氵@個(gè)js文件需要依賴的東西,例如:上面index.js依賴了jquery.js goTop.js.......
function(){}: 回調(diào)函數(shù),加載完依賴后需要執(zhí)行的東西

5. 相應(yīng)的子js文件的解析
 * goTop.js

//定義goTop.js需要的依賴(jquery),在回調(diào)函數(shù)中用$使用jquery
define(['jquery'],function($){
function GoTop($ct){
this.$ct=$ct;
this.bind()
this.init()
}
GoTop.prototype.bind=function(){
if($(window).scrollTop()>50){
this.$ct.fadeIn()
this.$ct.on('click',function(){
$(window).scrollTop(0)
})
}
else {
this.$ct.fadeOut()
}
}
GoTop.prototype.init=function(){
var _this=this
$(window).on('scroll',function(){
_this.bind()
})
}

//return 出來(lái)
return GoTop

})
// 記住這里一定要,一定要,
//一定要return 出來(lái)給其它的js文件引用,
//就像index.js中define引用的goTop
//得到的就是我們r(jià)eturn的GoTop構(gòu)造函數(shù)。
//然后就可以new相應(yīng)的構(gòu)造函數(shù)得到相應(yīng)的效果

* Waterfall.js

//定義Waterfall.js需要的jquery依賴
define(['jquery'],function($){
function Waterfall($ul) {
this.$ul=$ul;
this.$itemLi =this.$ul.find('.item-li') ;
this.btn=this.$ul.siblings(".item-btn")
this.init();
this.getData();
this.event()
}
Waterfall.prototype.init=function(){

        this.$itemLiWidth = this.$itemLi.outerWidth(true);
        this.arrLength = parseInt(this.$itemLi.parents('.wrap').width() / this.$itemLiWidth)
        this.pageCount= this.arrLength*2;
        this.curPage=1;
        this.dataIsArrive=false
        this.arr=[];
        //初始化數(shù)組
        for(var i=0;i<this.arrLength;i++){
            this.arr.push(0)
        }
    }
    Waterfall.prototype.event=function(){
        var _this=this;
        if(!this.dataIsArrive){
            this.btn.on('click',function(){
                _this.getData()
                _this.dataIsArrive=true
            })
        }
    }

    Waterfall.prototype.show = function ($node) {
        var top = $node.offset().top;
        var scr = $(window).scrollTop();
        var winHeight = $(window).height()
        if (top < scr + winHeight) {
            return true
        }
        else return false
    }
    Waterfall.prototype.getData = function () {
        var _this=this;
        if (!this.dataIsArrive) {
            $.ajax({
                method: "GET",
                url: "http://platform.sina.com.cn/slide/album_tech",
                dataType: "jsonp",
                jsonp: "jsoncallback",
                // http://platform.sina.com.cn/slide/album_tech?jsoncallback=func&app_key=1271687855&num=3&page=4
                data: {
                    app_key: "1271687855",
                    num: this.pageCount,
                    page: this.curPage
                }
            }).done(function(res){
                // console.log(res.data)
                _this.curPage++
                _this.place(res.data)  //得到10條數(shù)據(jù)

                _this.dataIsArrive=false
            })
        }
        dataIsArrive=true
    }
    Waterfall.prototype.place=function(items){
        var _this=this
        this.$tpls=this.create(items);
        // console.log(this.$tpls)
        // console.log(this.$tpls.html())
        // console.log()
        $.each(this.$tpls,function(index,ele){
            var $node=$(ele);
            $node.find("img").on('load',function(){
                _this.$ul.append($node);
                _this.waterfall($node)                })
        })
    }
    Waterfall.prototype.waterfall=function($node){
        var idx=0,min=this.arr[idx]
        for(var i=0;i<this.arr.length;i++){
            if(this.arr[i]<min){
                idx=i
                min=this.arr[i]
            }
        }
        $node.css({
            top: min,
            left: idx*this.$itemLiWidth
        })
        // console.log($node.outerWidth(true))
        // console.log($node.outerHeight(true))
        this.arr[idx]=$node.outerHeight(true)+this.arr[idx]
        this.$ul.height(Math.max.apply(null,this.arr))
    }
    Waterfall.prototype.create=function(nodes){
        var tpls='';
        for(var i=0;i<nodes.length;i++){
            tpls+="<li class='item-li'>";
            tpls+="<a href="+nodes[i].url+">";
            tpls+="![](+nodes[i].img_url+)";
            tpls+="</a>"
            tpls+="<h4 class='title'>"+nodes[i].short_name+"</h4>"
            tpls+="<p class='desp'>"+nodes[i].short_intro+"</p>"
            tpls+="</li>"
        }
        return $(tpls)
    }
return Waterfall

//返回Waterfall構(gòu)造函數(shù)給其它的文件使用
})

6. 打包所有的js文件,減少服務(wù)器請(qǐng)求

//全局安裝requirejs打包js
npm install -g requirejs

7. 配置相應(yīng)的路徑文件打包
我們需要給r.js一個(gè)配置文件來(lái)打包所有的js文件,并且配置文件baseUrl找到我們r(jià)equirejs.config配置的baseUrl
例如:build.js文件

({
// 這里的baseUrl和我們之前設(shè)置的入口文件main.js的baseUrl的區(qū)別
baseUrl:'../../js/lib', //以自己的位置為準(zhǔn) 找到和requirejs.config的baseUrl的位置一樣的文件夾
paths: {
app: '../app'
},
name: "app/main", //baseUrl+paths定位到main.js
out: "../dist/merge.js" //解析main.js并轉(zhuǎn)換存放在當(dāng)前文件的上級(jí)目錄的dist文件中
})

8. 切換到build.js的文件夾下運(yùn)行打包

r.js -o build.js //打包js文件

![打包減少請(qǐng)求](http://upload-images.jianshu.io/upload_images/3635292-b7904d56fe145165.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

### [requirejs官網(wǎng)](http://www.requirejs.cn/)
  ?
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容