Requirejs的作用
传统的Javascript开发,往往使用script导入的方式来使用不同的Javascript文件,这样页面必须一次性导入所有的Javascript文件。Requirejs使用了不同于传统<script>标签的脚本加载步骤,它可以在Javascript代码运行过程中,动态的载入Javascript文件,并且管理载入的文件。因此可以用它来加速、优化代码,最终目的为了代码的模块化。
如何获取Requirejs
Requirejs的官网。
Requirejs的兼容性
IE 6+ .......... compatible ✔
Firefox 2+ ..... compatible ✔
Safari 3.2+ .... compatible ✔
Chrome 3+ ...... compatible ✔
Opera 10+ ...... compatible ✔
Requirejs的使用
RequireJS以一个相对于baseUrl的地址来加载所有的代码。 页面顶层
<!--This sets the baseUrl to the "scripts" directory, and
loads a script that will have a module ID of 'main'-->
<script data-main="scripts/main.js" src="scripts/require.js"></script>
Requirejs是一个极其精简的框架,并支持多个浏览器。
一个简单的例子:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Requirejs测试</title>
<script src="js/require.js"></script>
<script src="js/index.js"></script>
</head>
<body>
</body>
</html>
index.js
require(['js/a']);
a.js
alert("a");
在服务端运行index.html的时候,会弹出对话框,显示a,说明js文件夹下的a.js载入了。
define方法
用define方法,可以声明js文件里的模块。
如:
define(function() {
alert("a");
})
可能你会有疑问,define这个方法有什么用,不写也是一样的效果,其实并不是。
在define里面的代码不会污染全局作用域,这个在非常复杂的OPA页面非常重要。
加载多个模块
修改index.js, 在require方法的参数数组,加一个模块。
require(['js/a', 'js/b']);
我们会发现,requirejs载入多个模块也是没问题的。
模块加载完成的事件
require(['js/a', 'js/b'], function() {
console.log("module is all loaded");
});
引入外网JS
require.config({
paths : {
"jquery" : ["http://libs.baidu.com/jquery/2.0.0/jquery.min"]
}
})
require(['jquery', 'js/a', 'js/b'], function() {
console.log("$", $);
console.log("module is all loaded");
});
require.config
require.config是用来配置模块加载位置,简单点说就是给模块起一个更短更好记的名字
require.config({
paths : {
"jquery" : ["http://libs.baidu.com/jquery/2.0.0/jquery.min"],
'a': 'js/a',
'b': 'js/b'
}
})
require(['jquery', 'a', 'b'], function() {
console.log("$", $);
console.log("module is all loaded");
});
通过paths的配置会使我们的模块名字更精炼,paths还有一个重要的功能,就是可以配置多个路径,如果远程cdn库没有加载成功,可以加载本地的库.
shim 配置第三方插件
通过require加载的模块一般都需要符合AMD规范即使用define来申明模块,但是部分时候需要加载非AMD规范的js,这时候就需要用到另一个功能:shim,shim解释起来也比较难理解,shim直接翻译为"垫",其实也是有这层意思的,目前我主要用在两个地方\
- 非AMD模块输出,将非标准的AMD模块"垫"成可用的模块,例如:在老版本的jquery中,是没有继承AMD规范的,所以不能直接require["jquery"],这时候就需要shim,比如我要是用underscore类库,但是他并没有实现AMD规范,那我们可以这样配置
require.config({
shim: {
"underscore" : {
exports : "_";
}
}
})
也可以简写为:
require.config({
shim: {
"underscore" : {
exports : "_";
},
"jquery.form" : ["jquery"]
}
})
这样配置之后我们就可以使用加载插件后的jquery了
require.config(["jquery", "jquery.form"], function($){
$(function(){
$("#form").ajaxSubmit({...});
})
})