[英]Dynamically Included Javascript and Dependencies
因此,作為我自己的一種鍛煉,我正在編寫一個異步腳本加載器實用程序(認為require.js,head.js,yepnope.js),並且遇到了一些難題。 首先,基本語法如下:
using("Models/SomeModel", function() {
//callback when all dependencies loaded
});
現在,我想知道在進行此調用時,我所處的文件是什么。我可以使用ajax調用來完成該操作,以便可以在內容加載之后但在進行評估以標記所有內容之前標記一個標志使用調用將用於特定文件,然后在eval之后立即取消設置標志(我知道eval是邪惡的,但在這種情況下,它首先是javascript而不是json,因此不是AS邪惡)。 我很確定這可以滿足我的需要,但是出於以下幾個原因,我更願意使用script標簽來做到這一點:
我嘗試了幾乎可以滿足我需要的東西。 我保留每次使用被調用的列表。 當加載其中一個腳本時,我將使用其中的任何引用,並將其合並到剛加載的文件的正確對象中,並清除全局列表。 這實際上在Firefox和Chrome中似乎可以正常運行,但在IE中失敗,因為加載事件似乎在怪異的時間發生了(jQuery引用吞噬了對另一種類型的引用,並最終將其顯示為依賴項)。 我以為我可以鎖定“交互式”就緒狀態,但似乎從未發生過。
所以現在我來問一下這里是否有人有任何想法。 如果大家都想要,我可以發布代碼,但是它仍然很凌亂並且可能很難閱讀。
編輯:其他用法
//aliasing and multiple dependencies
using.alias("ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js", "jQuery");
using(["jQuery", "Models/SomeModel"], function() {
//should run after both jQuery and SomeModel have been loaded and run
});
//css and conditionals (using some non-existant variables here)
using.css({ src: "IEFix", conditionally: browser === "MSIE" && version < 9 });
//should include the IEFix.css file if the browser is IE8 or below
並在下面詳細說明我的回答,請考慮將其視為文件A(並考慮之前的jquery別名仍然存在):
using(["jQuery", "B"], function() {
console.log("This should be last (after both jQuery and B have loaded)");
console.log(typeof($));
});
那么這將是B:
using("C", function() {
console.log("This should be second");
});
最后,C:
console.log("This should be first");
輸出應為:
This should be first
This should be second
This should be last (after both jQuery and B have loaded)
[Object Object]
值得稱贊的是您正在從事這樣的教育項目。
但是,您將無法以您想要的方式完成它。
好消息是:
實際上,您在那里擁有所需的一切: function reference.
一個callback
,如果可以的話。
您的using
函數的粗略P代碼為:
function using(modules, callback) {
var loadedModules = []
// This will be an ajax call to load things, several different ways to do it..
loadedModules[0] = loadModule(modules[0]);
loadedModules[1] = loadModule(modules[1]);
// Great, now we have all the modules
// null = value for `this`
callback.apply(null, loadedModules);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.