Detect jQuery using regular javascript, if not, load it dynamically

I need code to use regular javascript to determine if jQuery is present, if not, download the jQuery file from Google or another website.

UPDATE Two working solutions (just copy and paste 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(); 
+4
source share
3 answers

Something like this should work.

EDIT: Code added from the link above.

 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(); 
+2
source

There are many ways I like it the most because it is less detailed

 <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> 
+14
source

A good 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 result in an asynchronous load, so you might want to enable the .onload handler to execute execution until the download is complete.

+9
source

Source: https://habr.com/ru/post/1414033/


All Articles