AMD(異步模塊定義),是實現JavaScript模塊化規範之一,它採用異步方式加載模塊,模塊的加載不影響後面語句的運行。require.js和curl.js都是實現AMD規範的優秀加載器。本文采用require.js。css
1. define用於模塊定義html
define(模塊ID,依賴模塊數組,實例化模塊函數);模塊ID和依賴模塊數組爲可選。jquery
如:數組
define("color",["jquery"],function($){ +function(){ $.fn.extend({ "color":function(value){ if(value==undefined){ return this.css("color"); }else{ return this.css("color",value); } } }); }(); });
2. require處理依賴加載curl
require(模塊數組,回調函數);第一個參數爲要加載的模塊數組,第二個參數爲模塊加載後的回調函數。異步
如:async
require(['test'], function (test){ test.testMath(); test.testColor(); });
1. math.js模塊化
define("math1",function(){ var add = function (x,y){ return x+y; }; var minus = function(x,y){ return x-y; }; return { add: add, minus:minus }; });
2. jquery.color.js函數
jquery1.7以上已經實現AMD規範。ui
define("color",["jquery"],function($){ +function(){ $.fn.extend({ "color":function(value){ if(value==undefined){ return this.css("color"); }else{ return this.css("color",value); } } }); }(); });
3. test.js
define("test",["math1","color","jquery"],function(math,color,$){ var testMath=function(){ var x=10; var y=5; $("#divAdd").html(x+"+"+y+"="+math.add(x,y)); $("#divMinus").html(x+"-"+y+"="+math.minus(x,y)); }; var testColor=function(){ $("#divColor").color("blue"); }; return { testMath:testMath, testColor:testColor } });
4. main.js
require.config({ paths: { "jquery": "jquery-3.2.1.min", "color": "jquery.color", "math1": "math", "test":"test" } }); require(['test'], function (test){ test.testMath(); test.testColor(); });
5. index.html
<!DOCTYPE html> <html> <head> <script src="js/require.js" data-main="js/main" defer async="true"></script> </head> <body> <div id="divAdd">testAdd</div> <div id="divMinus">testMinus</div> <div id="divColor">testColor</div> </body> </html>