0

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

nyfer
  • 153
  • 1
  • 12

1 Answers1

0

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.");
});
Dylan Valade
  • 5,565
  • 6
  • 42
  • 56
  • ReferenceError: $ is not defined $.getScript( "http://code.jquery.com/jquery-1.10.1.min.js" ) guess you did not get my question properly. i want to use jquery in my external js. e.g in test.js – nyfer Oct 21 '13 at 19:12
  • You want to use `getScript` from the jQuery library to load the jQuery library? – Quentin Oct 21 '13 at 19:14
  • how we can use getScript without loading jquery file?? We need to load the jquery before we can use $ variable . So how to do that? – nyfer Oct 21 '13 at 19:17
  • You can't use jquery to load jquery. You won't have access to the `$` variable until jquery is included. This question probably has an option you could use http://stackoverflow.com/questions/13121948/dynamically-add-script-tag-with-src-that-may-include-document-write – Dylan Valade Oct 21 '13 at 19:51
  • Read my question please. i know that i cant use jquery to load jquery. I have used javascript to do it , any other better method using javascript can you suggest ? – nyfer Oct 22 '13 at 01:52
  • Do you have a URL to look at where this is happening? I always put `` in the HTML and any external scripts after it so they will all have access to jQuery – Dylan Valade Oct 22 '13 at 04:03
  • i dont want to use in HTML file. but instead use var src='http://code.jquery.com/jquery-1.10.1.min.js'; document.write(' '); in my js e.g test.js which i will load in my HTML file – nyfer Oct 22 '13 at 06:16
  • Sorry pal, not sure what else to do for you. Good luck – Dylan Valade Oct 22 '13 at 06:33