2013-06-18 88 views
0

我是jquery的新手,想問一個簡單的問題。我有一個jQuery文件說asdfg.js首先追加jquery文件(更改js文件的順序)

此文件需要jquery.js

在這個文件中,我正在檢查jquery.js是否已經加載。如果jquery未加載,請包含js文件。

我使用下面的代碼:

if (window.jQuery) { 
    alert("jQuery library is loaded!"); 
} else { 
    var elmScript = document.createElement('script'); 
    elmScript .src = 'http://localhost/new_customer/js/jquery-1.7.2.min.js'; // change file to your jQuery library 
    elmScript .type = 'text/javascript'; 
    document.getElementsByTagName('head')[0].appendChild(elmScript); 
} 

但這個文件加載jquery.jsasdfg.js文件,在其中我工作。那麼,如果我想在asdfg.js之前加載這個jquery.js,我該怎麼辦?

+0

你爲什麼不只是包括jQuery的在你的HTML你'包括前asdfg.js'? – Broxzier

回答

1

把你的代碼放到一個函數中,如果jQuery被加載,直接調用它,否則把它放到腳本元素上的.onload

喜歡的東西:

if(window.jQuery) { 
    myCode(); 
} else { 
    var elmScript = document.createElement('script'); 
    elmScript.src = 'http://localhost/new_customer/js/jquery-1.7.2.min.js'; // change file to your jQuery library 
    elmScript.type = 'text/javascript';   
    elmScript.onload = myCode; 
    document.getElementsByTagName('head')[0].appendChild(elmScript); 
} 

function myCode() { 
    // use jQuery here... 
} 
+0

這是說mycode沒有被定義 –

+0

@lord_linus,你需要把你的代碼中使用jQuery的所有內容放在那個函數中,所以它會在它應該運行時運行。 – Dogbert

+0

感謝Dogbert,這個答案解決了我的問題,實際上問題是區分大小寫 –

1

的你,而不是可以嘗試這樣的事:

document.getElementById("myList").insertBefore(newItem,existingItem); 
+0

prependChild呵? – lifetimes

+1

謝謝你Zenith ..沒有prependchild – karthi

+0

嘿meenakshi,如果我不知道div的Id,該怎麼辦? –