Reputation: 4387
I'm trying to handle JQuery not loading.
(this is for a javascript api, frequently the developer consuming it forgets to include jquery, hence I want to instruct them on what is missing)
(function ($, undefined) { //stuff })( jQuery );
If JQuery is not loaded then the code above breaks. A workaround I've found is to add a check for Jquery instead through a function e.g.
(function ($, undefined) {
//stuff
})( JQueryCheck() );
function JQueryCheck() {
if (window.jQuery == undefined)
alert("no jquery");
else
return jQuery;
}
I'm not sure if this is strong enough, if theres a better way to do it then let me know.
This must be common issue but I'm struggling to find a solution.
Upvotes: 0
Views: 921
Reputation: 3490
Try this:
function JQueryCheck() {
return !!jQuery;
}
Or:
function JQueryCheck() {
try{
jQuery();
} catch(e){
if(e){
return false;
} else {
return true;
}
}
}
Or:
function JQueryCheck() {
if(window.jQuery){
return true;
}else{
return false;
}
}
Good luck!
Upvotes: 2
Reputation: 76229
Your code should work fine, but you could simplify it a bit:
(function ($, undefined) {
if(!$) {
return alert("no jquery");
}
//stuff
})(window.jQuery);
You could also just load it when it's not loaded already:
(function (undefined) {
if(!window.jQuery) {
var script = document.createElement("SCRIPT");
script.src = 'http://code.jquery.com/jquery-2.1.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback();
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(main);
} else {
main();
}
}());
function main() {
alert("jquery loaded");
};
Taken from https://stackoverflow.com/a/10113434/941764
Upvotes: 1
Reputation: 59252
Don't load script files like this <script src="some-path"></script>
in Html
instead do this:
if(window.jQuery){
$.getScript('path to js file');
}
This checks for jquery and if it exists, it loads the script and executes it.
Upvotes: 3
Reputation: 10447
Whilst it would be best to solve the issues you are having with it not loading this will do what you want it to:
if(window.jQuery) {
//jQuery Code
}
Alternatively if you're after loading a local file if a hosted one has failed, this would work:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery.min.js"><\/script>')</script>
Upvotes: 1