简体   繁体   中英

load jquery in external javascript file

I want to load jquery in an external js file and use it. Am doing it in test.js the below given way

   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
  });
 }

Am getting $ reference error if do not call function init() onload. any other better method , then suggest me. Thanks

Try using getScript instead.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM