2011-01-18 89 views
1

我想作這樣的事情(類似於):如何在JavaScript中實現`使用`?

using("content/jquery.js"); 

$("div").fadeOut(); 

所以,如果content/jquery.js是不是在head我想加載它,它加載後繼續執行的script

是否有可能實現這個或類似的東西?注意:我可以有多於1個using

回答

4

這些被稱爲腳本加載器。

你可以看看RequireJS,其行爲在一個非常相似的方式:

require(["helper/util"], function() { 
    //This function is called when scripts/helper/util.js is loaded. 
}); 

還有LabJSControlJS,這是更側重於異步腳本加載,而不是依賴關係,但可能是值得一試出。同樣在這個類別中,我們擁有@ jAndy的SupplyJS

+0

不要忘記supplyJS:O)https://github.com/jAndreas/Supply – jAndy 2011-01-18 23:12:28

1

如果你知道你將調用的時間提前函數的名稱,你可以使用typeof來檢查他們的存在:

if (typeof($) == 'function') { 
    // Code here that uses jQuery 
} else { 
    // Something else here that loads the script. 
} 

如果你不能確定你會使用什麼功能您可能想要檢索腳本元素的列表並檢查它們。更多沿着這些線:

var scripts = document.getElementsByTagName('script'); 

for (var i = 0, l = scripts.length; i < l; ++i) { 
    if (scripts[i].src == myVal) { 
    // do something here 
    } else { 
    // wait for the script to load, or just leave off the else. 
    } 
} 

是我能想到的兩種方法我的頭頂。

2

您可以使用getScript

$.getScript('test.js', function() { 
    alert('Load was performed.'); 
}); 
+0

+1很好的答案,我忘了。這很有趣,因爲在這個例子中,OP正在嘗試加載jQuery,而使用jQuery。但是你必須有一些腳本來啓動它,這取決於你的需求。 – 2011-01-18 23:20:29