I have the following code in an external JS file (ie: test.js); which creates an additional script tag pointing to a JQuery source if it detects that a JQuery source isn't already there. The code actually creates the script tag and inserts it before the actual script that's doing the creating:
if (typeof(jQuery) == "undefined") {
var head = document.getElementsByTagName("head")[0];
// get any and all script tags
var scripts = document.getElementsByTagName("script");
// the actual script call the actions (ie: this one "test.js")
thisScript = scripts[scripts.length - 1];
// create element
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
head.insertBefore(script,thisScript);
}
The above works fine. However, the problem I'm having is that once the JQuery source script tag is created, the rest of the code on "test.js" doesn't work. It's as if the code can't access the JQuery functions (or doesn't know that JQuery is there).
Thus, the following code on "test.js" doesn't work:
$(document).ready(function() {
// ...
});
The error I'm getting according to FireBug with FF 12 is: "$ is not defined" Any ideas as to why this is happening or how I can fix it?
NOTE: I know I can just place JQuery on target page; however, that isn't an option as the code has to be able to detect if JQuery is there; and if not, then create the script tag pointing to JQuery and run the Jquery code.