requirejs

requrejs 可以解决的问题:
1.逻辑比较复杂的js可能会有上千行js代码 此时我们开发和维护起来会有非常大的难度和不方便的地方,所以我们用requirejs模块化js
2.可以异步加载js,如果有需要同步的地方也可以实现 避免同步加载js延缓页面加载速度问题
requrejs 目录:
require_test
    js
      app_js
        index.js
        open.js
        other.js
      lib_js
        jquery.js
      main.js
      require.js
  index.html
requrejs配置和使用:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script data-main="js/main.js" src="js/require.js"></script>
</head>
<body>
<h1>hello</h1>
<button id="btn">click button</button>
<script>
require(['js/app_js/index.js']);
require(['js/app_js/open.js']);
</script>
</body>
</html>
main.js
require.config({
baseUrl : 'js/lib_js/', //定义了baseUrl后只能在这个目录下写文件
path : {
// 'index' : 'js/app_js/index',
// other : '../app_js/other.js'
// 'others' : '../app_js/other'
}
});
/*baseUrl 是写的除了cdn的主要目录
path 是相对与baseUrl来进行的 也就是path 是在baseURL下面的路径
path 下面写相对上一级目录会报错找不到
define 要避免使用定义名
*/
index.js
require(['jquery','../app_js/other'],function($,o) {
$(function(){
alert(112);
$('#btn').click(function(){
$(this).css('display','none');
});
o.fn1();
o.fn2();
})
 
});
other.js
define([],function(){
var init = {};
init.fn1 = function(){
alert(12345);
}
init.fn2 = function(){
alert(4567);
}
return init;
})
open.js
require(['jquery'],function($){
alert('hello zero')
})
 
原文地址:https://www.cnblogs.com/zerohu/p/5647190.html