2013-10-21 133 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