模快化的发展史

2017-03-28  本文已影响51人  sunny519111

世人皆醒,为我独醉,人生何苦如此---sunnyhuang

题目1: 为什么要使用模块化?

  1. 解决命名冲突
  2. 依赖管理
  3. 可以提高代码的可读性
  4. 提高代码的复用性
  5. 避免污染全局变量

题目2:CMD、AMD、CommonJS 规范分别指什么?有哪些应用

不同的运用
gulp和webpackgulp和webpack

requirejs详解

  1. 首页加载require.js的文件

    <script data-main="scripts/main.js" src="scripts/require.js"></script>
    //首先浏览器不会识别data-main属性的地址,
    

//当require.js加载完成后,发现require.js里有data-main的内容,
//就会回头加载data-main里面的位置资源

2. require.config() 配置文件,配置资源的入口
![事例文件夹配置](https://img.haomeiwen.com/i3635292/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规范的调用

//1. 没有回调函数,就会直接调用依赖
define([jquery])
//2. 有回调函数,没有依赖
//main.js
define(function(){
var add = function(x, y) {
return x + y;
};
return {
add: add
};
})
//3. 有依赖,需要指明依赖数组
define(['myMoudel','jquery'],function(mymoudel,$){
function foo(){
dosomething() .....
}
return {
foo:foo
}
})


### 项目实际运用
![根目录列表](https://img.haomeiwen.com/i3635292/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>`
**解析:**当浏览器加载到require.js,加载完成后,会去寻找data-main里面的脚本运用到页面中
2. 当解析完成后,会找到相应路经的main.js文件

requirejs.config({
baseUrl: './js/lib', //相对于根路径而已(index.html)
paths: {
'app': '../app' //设置简写的路径
}
});
//加载模快入口
requirejs(['app/index']);
//配置文件main.js的baseUrl是相对于index.html而言
//配置完require.config后,需要加载模快,
//对于没有回调函数,就会直接调用依赖,依赖位置在./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"))  //瀑布流

})

**解析:** 由于我们已经设置了main.js的基本目录,后面所有加载的js文件都是根据baseUrl+paths的路经,所以./js/lib下面的js插件都可以直接运用名字(后缀名js省略)
> 相当于加载jquery.js / goTop.js / Carousel.js / Waterfall.js  并给它传入到相应的回调函数的形参,用来调用相应的方法。

4. 解析define的用法
为什么`define(['jquery','goTop','Carousel','Waterfall'],function(){.....}`之后就会有相应的方法和函数出来呢?

define('id',[],function(){})
id: 模快名字,给一个js文件取一个名字
[] : 模快依赖,就是你这个js文件需要依赖的东西,例如:上面index.js依赖了jquery.js goTop.js.......
function(){}: 回调函数,加载完依赖后需要执行的东西

5. 相应的子js文件的解析
 * goTop.js

//定义goTop.js需要的依赖(jquery),在回调函数中用$使用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构造函数。
//然后就可以new相应的构造函数得到相应的效果

* 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=[];
        //初始化数组
        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条数据

                _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构造函数给其它的文件使用
})

6. 打包所有的js文件,减少服务器请求

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

7. 配置相应的路径文件打包
我们需要给r.js一个配置文件来打包所有的js文件,并且配置文件baseUrl找到我们requirejs.config配置的baseUrl
例如:build.js文件

({
// 这里的baseUrl和我们之前设置的入口文件main.js的baseUrl的区别
baseUrl:'../../js/lib', //以自己的位置为准 找到和requirejs.config的baseUrl的位置一样的文件夹
paths: {
app: '../app'
},
name: "app/main", //baseUrl+paths定位到main.js
out: "../dist/merge.js" //解析main.js并转换存放在当前文件的上级目录的dist文件中
})

8. 切换到build.js的文件夹下运行打包

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

![打包减少请求](https://img.haomeiwen.com/i3635292/b7904d56fe145165.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

### [requirejs官网](http://www.requirejs.cn/)
  ​
上一篇 下一篇

猜你喜欢

热点阅读