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(); 
1

3 Answers 3

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> 
Sign up to request clarification or add additional context in comments.

5 Comments

I didn't see your answer until later. Strange. Your code works. Thanks
ugh. I clicked downvote by accident -- should have been upvote, but now it's locked-in until question is edited. sorry about that, chief.
@Michael Paulukonis: no problem. Edited answer in case you're interested in reverting your vote.
the line src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" produces an error in Webkit which I corrected adding the protocol http.
@Francisco // is dynamic protocol, that means it will adopt whatever protocol is currently in use
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.

1 Comment

onload doesn't seem to work always: stackoverflow.com/questions/3248384/…
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(); 

1 Comment

Thanks. Worked out well. I added the working code into my question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.