*
參考文章:requireJs簡要介紹和完整例子
按照這篇文章自己動手寫了一個例子,做了小修改
一:目錄
二:源碼
0,index.html
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Home</title> <style type="text/css"> *{font-family:"微軟雅黑","microsoft Yahei",verdana;} .text01{line-height:20px;font-size:13px;font-family:verdana;} pre{margin:0px;padding:2px 0px;font-size:13px;font-family:verdana;} .div01{border:1px solid red;text-align:left;padding:5px; } </style> </head> <body> <h4>requireJS 例子 example 01</h4> <div id="loadMsgCon" class="div01"></div> <script data-main="scripts/main" src="scripts/require.js"></script> <!--注意 requireJS 文件對應即可,同時data-main屬性值寫對即可--> </body> </html>
1,main.js
//1,about require js config//配置信息 ; require.config({ //define all js file path base on this base path //actually this can setting same to data-main attribute in script tag //定義所有JS文件的基本路徑,實際這可跟script標簽的data-main有相同的根路徑 baseUrl:"./scripts" //define each js frame path, not need to add .js suffix name //定義各個JS框架路徑名,不用加后綴 .js ,paths:{ "jquery":["http://libs.baidu.com/jquery/2.0.3/jquery", "lib/jquery/jquery.min"] //把對應的 jquery 這里寫對即可 ,"workjs01":"work/workjs01" ,"workjs02":"work/workjs02" ,"underscore":"" //路徑未提供,可網上搜索然后加上即可 } //include NOT AMD specification js frame code //包含其它非AMD規范的JS框架 ,shim:{ "underscore":{ "exports":"_" } } }); //2,about load each js code basing on different dependency //按不同先后的依賴關系加載各個JS文件 require(["jquery","workjs01"],function($,w1){ require(['workjs02']); });
2,workjs01.js
define(['jquery'],function($){ //注意模塊的寫法 //1,define intenal variable area//變量定義區 var myModule = {}; //推薦方式 var moduleName = "work module 01"; var version = "1.0.0"; //2,define intenal funciton area//函數定義區 var loadTip = function(tipMsg, refConId){ var tipMsg = tipMsg || "module is loaded finish."; if(undefined === refConId || null === refConId || "" === refConId+""){ alert(tipMsg); }else{ $('#' + (refConId+"")).html(tipMsg); } }; //3,should be return/output a object[exports/API] if other module need //如有需要暴露(返回)本模塊API(相關定義的變量和函數)給外部其它模塊使用 myModule.moduleName = moduleName; myModule.version = version; myModule.loadTip = loadTip; return myModule; /* //this is same to four line code upper//跟上面四行一樣 return { "moduleName":"work module 01" ,"version":"1.0.0" ,loadTip:loadTip }; */ });
3, workjs02.js
define(['workjs01'],function(w01){ //1,define intenal variable area//變量定義區 var moduleName = "work module 02"; var moduleVersion = "1.0.0"; //2,define intenal funciton area//函數定義區 var setHtml = function(refId,strHtml){ if(undefined === refConId || null === refConId || "" === refConId+""){ return; }else{ $('#' + (refId + "")).html(strHtml+""); } }; //3,auto run when js file is loaded finish //在JS加載完,可在本模塊尾部[return之前]運行某函數,即完成自動運行 w01.loadTip("本頁文件都加載完成,本頁設計 workjs01.js 文件依賴jquery, workjs02.js 依賴 workjs01.js","loadMsgCon"); //4,should be return/output a object[exports/API] //如有需要暴露(返回)本模塊API(相關定義的變量和函數)給外部其它模塊使用 return { "moduleName":moduleName ,"version": moduleVersion } });
三:運行頁面
*