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
Sorry, scratch that. Didnt quite know what you were doing.
Try this:
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:
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:I used this code before, and it worked: