Reputation: 7740
I'm working within a platform that I do not have server side access to. That means I can't load javascript files directly into the head, only the body.
Here's how I'm doing my loads:
function loadjscssfile(filename, filetype){
//http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
loadjscssfile('https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js','js');
loadjscssfile('http://redacted.com/data.php?rand='+Math.random(),'js');
However, the third javascript file (a jQuery plugin) I load requires jQuery.
When I load the page I get this error (in Chrome)
Uncaught ReferenceError: jQuery is not defined
My inclination is that my plugin is loading before jQuery. Because if I refresh the page (when jQuery is cached) the error disappears. However, I need this to work even when jQuery is not cached. Thoughts?
Upvotes: 2
Views: 2787
Reputation: 3695
As you're trying you have to load jQuery and run the other scripts after it loads. To do that you can use a loader library, like yepnope or headjs, remembering that as you cannot put scripts on your head you have to put the loader code along to the script.
Your code will be something like this:
yepnope( // or head.js
'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js',
'http://redacted.com/data.php?rand='+Math.random(),
'https://raw.github.com/aakilfernandes/jquery.inject/master/jquery.inject.js?rand='+Math.random()
);
Another thing you can do is just put the jquery script on the body and load the other scripts after it:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$.getScript('http://redacted.com/data.php?rand='+Math.random());
$.getScript('https://raw.github.com/aakilfernandes/jquery.inject/master/jquery.inject.js?rand='+Math.random());
</script>
Upvotes: 0
Reputation: 450
This is not an elegant solution but it works always for me: copy/paste the content of jquery.min.js file directly to your html page
<script> ... </script>
Upvotes: 1
Reputation: 1045
What I do is this
if (typeof $ === 'undefined') {
document.write("<script src='//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'><\/script>");
var timeout = 0;
while (typeof $ === 'undefined' && timeout++ < 100);
}
This will wait until jquery is loaded before it moved on to do anything else. Then load your plugin.
Upvotes: 0