我寫這取決於我想要有條件包括外部庫插件,也就是說,用戶可以選擇不在情況下,用戶的網站已經擁有了它們被自動包含那些圖書館。下面是一些僞代碼來說明問題有條件地加載外部JavaScript庫在我的插件
<script type="text/javascript" src="path/to/plugin.js"></script>
<script type="text/javascript">
PLUGIN.init({
"param1": "foo",
"parma2": 33,
"include": {"jquery": 0, "googlemaps": 0}
});
</script>
在我的插件腳本
var PLUGIN = {
"init": function(obj) {
if (obj.include.googlemaps !== 0) {
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
}
if (obj.include.jquery !== 0) {
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
}
.. do more things ..
}
的問題是,當我準備「做更多的事情,」似乎是庫沒有被加載然而。我得到一個錯誤,沒有找到jquery,或找不到谷歌地圖。我可以通過更改我的代碼來解決此問題
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
var PLUGIN = {
"init": function(obj) {
.. do more things ..
}
但現在用戶無法控制加載庫或不加載它們。建議?解決方法?
更新:感謝您的建議,你們所有人,但目前爲止沒有喜悅。這就是我在做什麼,發生了什麼。因爲我可能加載0或多個腳本(用戶可以選擇決定哪些腳本不需要加載),我做了我的代碼,像這樣
"importLib": function(libPath, callback) {
var newLib = document.createElement("script");
if (callback !== null) {
newLib.onload = callback;
}
newLib.src = libPath;
document.head.appendChild(newLib);
},
"init": function(obj) {
var scripts = [];
if (obj.include.googlemaps !== 0) {
scripts.push("http://maps.google.com/maps/api/js?sensor=true&v=3.6");
}
if (obj.include.jquery !== 0) {
scripts.push("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js");
}
if (obj.include.anotherlib !== 0) {
scripts.push("http://path/to/another/lib.js");
}
var len_scripts = scripts.length,
callback = null;
if (len_scripts > 0) {
for (var i = 0; i < len_scripts; i++) {
// add callback only on the last lib to be loaded
if (i == len_scripts - 1) {
callback = function() { startApp(obj) };
}
importLib(scripts[i], callback);
}
}
// Start the app rightaway if no scripts need to be loaded
else {
startApp(obj);
}
},
"startApp": function(obj) {
}
什麼情況是,火狐與attempt to run compile-and-go script on a cleared scope
錯誤嘎嘎叫着,和Safari不會收到該錯誤,但不會加載任何內容。有趣的是,Safari錯誤控制檯根本沒有顯示任何錯誤。好像Firefox的錯誤是,如果我的評論,錯誤消失行document.head.appendChild(newLib);
造成的,但當然,網頁無法正確加載。
首先,設置你在列表中的最後一個庫的回調不是你想要的:如果第一個庫來自一個非常慢的服務器會怎麼樣?在回調已經觸發後,它可能會在最後列出的腳本之後加載數秒。您應該使用計數器來計算所請求的庫的數量。每次加載一個lib時,觸發一個回調,即1)遞減計數器,2)如果計數器下降到0,則啓動應用程序。 – apsillers 2012-03-20 12:36:38
其次,嘗試搜索該錯誤文本。它看起來像清理緩存將修復它。 – apsillers 2012-03-20 12:39:18