2012-06-26 123 views
8

我遇到了用Javascript加載jQuery的問題。我需要使用Javascript加載它,因爲有條件我只能知道客戶端。註釋掉的代碼應該初始化腳本,但我沒有運氣。動態加載jQuery

var script_tag = document.createElement('script'); 
script_tag.setAttribute("type","text/javascript"); 
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js") 
//script_tag.onload = main; // Run main() once jQuery has loaded 
//script_tag.onreadystatechange = function() { // Same thing but for IE 
    //if (this.readyState == 'complete' || this.readyState == 'loaded') main(); 
//} 
document.getElementsByTagName("head")[0].appendChild(script_tag); 

http://mybsabusiness.com/samplesites/silver/sbsa01/

這是網站的問題上。

+1

你得到任何錯誤? 'main'做什麼? – Esailija

+2

究竟是什麼問題?該代碼工作得很好。 http://jsfiddle.net/4Euhk/ – sachleen

+0

向我們展示主要功能,這段代碼適用於我 –

回答

16

jQuerify bookmarlet

function getScript(url, success) { 
    var script = document.createElement('script'); 
    script.src = url; 
    var head = document.getElementsByTagName('head')[0], 
     done = false; 
    // Attach handlers for all browsers 
    script.onload = script.onreadystatechange = function() { 
     if (!done && (!this.readyState 
      || this.readyState == 'loaded' 
      || this.readyState == 'complete')) { 
     done = true; 
     success(); 
     script.onload = script.onreadystatechange = null; 
     head.removeChild(script); 
     } 
    }; 
    head.appendChild(script); 
} 
getScript('http://code.jquery.com/jquery-latest.min.js',function() { 
    // Yay jQuery is ready \o/ 
});​ 
+0

完美!謝了哥們 –