標籤:requirejs 按需載入
模組可以很好的定義範圍來避免全域名稱空間汙染,它可以顯示的定義出函數間的依賴關係,而不需要引用全域變數。
RequireJS可以載入多個不同的模組,雖然載入的順序不一樣,但是能保證依賴的順序是正確的。
1. 當模組中只有索引值對時,可通過如下方式定義。
define({ name : "beautiful", color: "yellow", size: "3M"});
2. 當模組中沒有依賴,只有函數時,模組的格式如下
define(function() {return { name : "beautiful", color: "yellow", size: "3M" }});
3. 當模組中有依賴函數時,先定義出依賴函數的路徑,依賴的函數的別名。
define(["./cart", "./inventory"], function(cart, inventory) { return { name : "beautiful", color: "yellow", size: "3M" addToCart: function() { inventory.decrement(this); cart.add(this); } } });
4. 將模組定義為函數
define(["my/cart", "my/inventory"], function(cart, inventory) { return function(title) { return title ? (window.title = title) : inventory.storeName + ‘ ‘ + cart.name; } });
通過上面的例子也許你已經注意到了,模組中的註冊的函數或對象都是在return中返回的。如果你自訂了一些函數應該模組通過return返回,否則模組是無法找到你定義的函數的。
本文出自 “這個人的IT世界” 部落格,請務必保留此出處http://favccxx.blog.51cto.com/2890523/1930268
Requirejs定義模組