4

I need the code to use regular javascript to detect whether or not JQuery is present, if not, load JQuery file from google or another website

UPDATE Two Working Solutions (just copying and pasting the working code here):

From Claudio Redi

window.jQuery || document.write("<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'>\x3C/script>")

From Rob Darwin

var jQueryScriptOutputted = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        if (! jQueryScriptOutputted) {
            jQueryScriptOutputted = true;
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    }
}
initJQuery();
Arghya C
  • 9,805
  • 2
  • 47
  • 66
Patriotec
  • 1,104
  • 4
  • 22
  • 43
  • 2
    Check this answer man http://stackoverflow.com/questions/1828237/check-if-jquery-has-been-loaded-then-load-it-if-false – eric.itzhak May 23 '12 at 21:28

3 Answers3

17

There are many ways, I like this most only because is the less verbose

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>  
<script>window.jQuery || 
    document.write("<script src='js/jquery-1.7.2.min.js'>\x3C/script>")
</script>   
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
11

The nice way to load jQuery without using document.write is:

if (window.jQuery === undefined) {
    var s = document.createElement('script');
    s.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js";
    document.head.appendChild(s);
}

This will cause an asynchronous load, though - so you may want to include a .onload handler to allow execution to wait until the load has finished.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • onload doesn't seem to work always: http://stackoverflow.com/questions/3248384/document-createelementscript-synchronously – Marius Jan 17 '17 at 06:47
3

Something like this should work.

EDIT: Code added from above link.

var jQueryScriptOutputted = false;
function initJQuery() {

    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {


        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;

            //output the script (load it from google api)
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {

        $(function() {  
            //do anything that needs to be done on document.ready
        });
    }

}
initJQuery();
Rob Darwin
  • 942
  • 1
  • 10
  • 17