2013-10-21 186 views
0

我想在外部js文件中加載jquery並使用它。 正在做它test.js下面給出的方式在外部JavaScript文件中加載jquery

var src='http://code.jquery.com/jquery-1.10.1.min.js'; 
    document.write('<sc'+'ript type="text/javascript" src="'+src+'" onload="init()">  </sc'+'ript>'); 

function init(){ 
     $(function(){ 
     //jquery code here 
    }); 
} 

我得到$引用錯誤,如果不調用函數的init() onload事件。 任何其他更好的方法,然後建議我。謝謝

回答

0

嘗試使用getScript來代替。

http://api.jquery.com/jQuery.getScript/

$.getScript("external.js") 
    .done(function(script, textStatus) { 
    init(); 
    }) 
    .fail(function(jqxhr, settings, exception) { 
    console.log("Triggered ajaxError handler."); 
}); 
+0

的ReferenceError:$沒有定義\t $ .getScript( 「http://code.jquery.com/jquery-1.10.1.min.js」) 想你沒有正確地得到我的問題。我想在我的外部js中使用jquery。例如在test.js – nyfer

+0

您想使用jQuery庫中的'getScript'來加載jQuery庫? – Quentin

+0

如何在不加載jquery文件的情況下使用getScript?在我們可以使用$變量之前,我們需要加載jquery。那麼該怎麼做? – nyfer