Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include jquery.js in another js file?

I want to include jquery.js in myjs.js file. I wrote the code below for this.

  var theNewScript=document.createElement("script");
  theNewScript.type="text/javascript";
  theNewScript.src="http://example.com/jquery.js";
  document.getElementsByTagName("head")[0].appendChild(theNewScript);
  $.get(myfile.php);

There shows an error on the 5th line that is '$ not defined'. I want to include jquery.js and then want to call $.get() function in myjs.js file. How can I do this? Please help me

like image 392
ajay Avatar asked Apr 07 '11 08:04

ajay


2 Answers

Appending a script tag inside the document head programmatically does not necessarily mean that the script will be available immediately. You should wait for the browser to download that file, parse and execute it. Some browsers fire an onload event for scripts in which you can hookup your logic. But this is not a cross-browser solution. I would rather "poll" for a specific symbol to become available, like this:

var theNewScript = document.createElement("script");
theNewScript.type = "text/javascript";
theNewScript.src = "http://example.com/jquery.js";
document.getElementsByTagName("head")[0].appendChild(theNewScript);
// jQuery MAY OR MAY NOT be loaded at this stage
var waitForLoad = function () {
    if (typeof jQuery != "undefined") {
        $.get("myfile.php");
    } else {
        window.setTimeout(waitForLoad, 1000);
    }
};
window.setTimeout(waitForLoad, 1000);
like image 199
Salman A Avatar answered Oct 12 '22 13:10

Salman A


The problem is that the script doesn't load instantly, it takes some time for the script file to download into your page and execute (in case of jQuery to define $).

I would recommend you to use HeadJS. then you can do:

head.js("/path/to/jQuery.js", function() {
   $.get('myfile.php');
});
like image 22
m0sa Avatar answered Oct 12 '22 12:10

m0sa