世人皆醒窝趣,為我獨醉,人生何苦如此---sunnyhuang
題目1: 為什么要使用模塊化勾给?
- 解決命名沖突
- 依賴管理
- 可以提高代碼的可讀性
- 提高代碼的復(fù)用性
- 避免污染全局變量
題目2:CMD滩报、AMD、CommonJS 規(guī)范分別指什么锦秒?有哪些應(yīng)用
![gulp和webpack](https://pic4.zhimg.com/v2-ae9253e557d902369b1beaed998061cb_b.jpg)
AMD(異步模塊定義):由于瀏覽器加載腳本天生異步露泊,AMD是一個在瀏覽器暮砹快化開發(fā)的規(guī)范旅择,但是由于元素的js并沒有define()和require(),所以AMD規(guī)范運用了requirejs庫。
-
** CMD(通用模板定義)**:也是異步加載模塊侣姆,它和AMD只是模塊定義的方式和模塊記載的時機(jī)不同
AMD和CMD的區(qū)別以及運用
- 都運用于瀏覽器端生真,AMD是異步加載資源沉噩,而CMD是松散加載資源,根據(jù)需求加載柱蟀。
- AMD是全部加載后川蒙,然后需求使用,而CMD是按需加載长已,就近依賴
- AMD在加載模塊完成后就會執(zhí)行模塊畜眨,所有模快都記載完成后术瓮,就會進(jìn)入required的回調(diào)函數(shù)康聂,執(zhí)行主邏輯函數(shù),胞四,這樣的效果就是依賴模塊的執(zhí)行順序和書寫順序不一定一致恬汁,看網(wǎng)絡(luò)速度,哪個先下載下來辜伟,哪個先執(zhí)行氓侧,但是主邏輯一定在所有依賴加載完成后才執(zhí)行。
- CMD加載完某個依賴模塊后并不執(zhí)行导狡,只是下載而已约巷,在所有依賴模塊加載完成后進(jìn)入主邏輯,遇到require語句的時候才執(zhí)行對應(yīng)的模塊烘豌,這樣模塊的執(zhí)行順序和書寫順序是完全一致的
//AMD define(['jquery','dailog','carousel'],function(jquery,dailog,Carousel){ var $=jquery; var dailog=dailog; var Carousel=Carousel; }) //CMD //1. 定義一個脑赝ィ快myModule.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就是運用這個規(guī)范囚聚,使用與同步加載資源,一個單獨的文件就是一個谋瓿快顽铸,每一個模快都有一個單獨的作用域料皇。
- 不需要引用其它的庫谓松,node.js自動封裝了一個2個對象用于模快的輸出和請求
- module.exports 募粒快的唯一出口鬼譬,我們需要把模快要輸出的東西放入該對象逊脯。
- require() 加載模塊使用
require
方法优质,該方法讀取一個文件并執(zhí)行,返回文件內(nèi)部的module.exports
對象
//定義一個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詳解
-
首頁加載require.js的文件
<script data-main="scripts/main.js" src="scripts/require.js"></script> //首先瀏覽器不會識別data-main屬性的地址,
//當(dāng)require.js加載完成后巩螃,發(fā)現(xiàn)require.js里有data-main的內(nèi)容演怎,
//就會回頭加載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庫(假如下載后的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. 沒有回調(diào)函數(shù)爷耀,就會直接調(diào)用依賴
define([jquery])
//2. 有回調(diào)函數(shù),沒有依賴
//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
}
})
### 項目實際運用
![根目錄列表](http://upload-images.jianshu.io/upload_images/3635292-d63146917d5ced4b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
1. 首頁引入require.js
`<script data-main="./js/app/main.js" src="./src/js/require.js"></script>`
**解析:**當(dāng)瀏覽器加載到require.js歹叮,加載完成后,會去尋找data-main里面的腳本運用到頁面中
2. 當(dāng)解析完成后铆帽,會找到相應(yīng)路經(jīng)的main.js文件
requirejs.config({
baseUrl: './js/lib', //相對于根路徑而已(index.html)
paths: {
'app': '../app' //設(shè)置簡寫的路徑
}
});
//加載牡琳停快入口
requirejs(['app/index']);
//配置文件main.js的baseUrl是相對于index.html而言
//配置完require.config后,需要加載某簦快票灰,
//對于沒有回調(diào)函數(shù),就會直接調(diào)用依賴,依賴位置在./js/lib/app/main.js
3. `./js/lib/app/main.js`里面的js文件加載頁面的主要功能
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插件都可以直接運用名字(后綴名js省略)
> 相當(dāng)于加載jquery.js / goTop.js / Carousel.js / Waterfall.js 并給它傳入到相應(yīng)的回調(diào)函數(shù)的形參,用來調(diào)用相應(yīng)的方法冯键。
4. 解析define的用法
為什么`define(['jquery','goTop','Carousel','Waterfall'],function(){.....}`之后就會有相應(yīng)的方法和函數(shù)出來呢惹盼?
define('id',[],function(){})
id: 模快名字惫确,給一個js文件取一個名字
[] : 氖直ǎ快依賴,就是你這個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 出來
return GoTop
})
// 記住這里一定要,一定要陈肛,
//一定要return 出來給其它的js文件引用揍鸟,
//就像index.js中define引用的goTop
//得到的就是我們return的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ù)器請求
//全局安裝requirejs打包js
npm install -g requirejs
7. 配置相應(yīng)的路徑文件打包
我們需要給r.js一個配置文件來打包所有的js文件阳藻,并且配置文件baseUrl找到我們requirejs.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)前文件的上級目錄的dist文件中
})
8. 切換到build.js的文件夾下運行打包
r.js -o build.js //打包js文件
![打包減少請求](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/)
?