How can I load jQuery if it is not already loaded?
Solution 1
jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>
). You would have to add an onload listener to the script (jqTag
) to detect when it loads and then run your code.
e.g.
function myJQueryCode() {
//Do stuff with jQuery
}
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
jqTag.onload = myJQueryCode;
headTag.appendChild(jqTag);
} else {
myJQueryCode();
}
Solution 2
To include jQuery you should use this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>
it uses the Google CDN but provides a fallback an has a protocol relative URL.
Note: Be sure to change the version number to the latest version
if window.jQuery
is defined, it will not continue to read the line since it is an or that already contains a true value, if not it wil (document.)write the value
see: theHTML5Boilerplate
also: you forgot the quotes, if jQuery is not defined:
typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong
you could also:
window.jQuery === undefined //true
Solution 3
If you're in an async function, you could use await
like this:
if(!window.jQuery){
let script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
}
/* Your jQuery code here */
If you're not, you can use (async function(){/*all the code*/})()
to wrap and run all the code inside one
.
Alternatively, refactoring Adam Heath's answer (this is more readable IMO). Bottom line, you need to run the jQuery code AFTER jQuery finished loading.
jQueryCode = function(){
// your jQuery code
}
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
Or you could also wrap it in a function to change the order of the code
function runWithJQuery(jQueryCode){
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
}
runWithJQuery(function jQueryCode(){
// your jQuery code
})
Solution 4
The YepNope loader can be used to conditionally load scripts, has quite a nice, easy to read syntax, they have an example of just this on their website.
You can get it from their website.
Example taken from their website:
yepnope([{
load: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('local/jquery.min.js');
}
}
}
Jeff
I'm a software engineer at Taxfyle, making taxes suck less. I am proficient in JavaScript and C#. http://www.Twitter.com/Jeffijoe
Updated on January 09, 2020Comments
-
Jeff over 4 years
I have a initializor.js that contains the following:
if(typeof jQuery=='undefined') { var headTag = document.getElementsByTagName("head")[0]; var jqTag = document.createElement('script'); jqTag.type = 'text/javascript'; jqTag.src = 'jquery.js'; headTag.appendChild(jqTag); }
I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isn't, adds it to the Head tag.
However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said:
"jQuery is undefined".
Is there a way to do this? Firebug shows the jquery inclusion tag within the head tag!
Also, can I dynamically add code into the
$(document).ready()
event? Or wouldn't it be necessary just to add some Click events to a few elements? -
Jeff almost 13 yearsThe js file I am including, will not be included at the top of the page, but rather within a div or something. Cant I use createElement method?
-
beardhatcode almost 13 yearsit should work, but you're not calling it see end of post, I would append it to the body. And you should always load JS on the end of the page (best practice for page speed/rendering)
-
Jeff almost 13 years@gar-onn - Why are you doing "==="? Firebug screams at me when I do it. I changed mine to if(typeof jQuery=="undefined")
-
AlienWebguy almost 13 yearsDid I miss the memo? Why are you and Steve telling Jeff to use an old version of JQuery?
-
beardhatcode almost 13 yearswas an old snipet, cahnged it to the current version
-
Jeff almost 13 yearsI would prefer doing this without any 3rd party libs
-
Jeff almost 13 yearsI would prefer doing this without any 3rd party libs :)
-
Jeff almost 13 yearsWill try that! add my button onclick handler in there, right?
-
beardhatcode almost 13 yearsit is the same lib, it only loads faster (witch is better), you can also use: code.jquery.com/jquery-1.6.2.min.js or an other from this site: docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery.
-
Adam Heath almost 13 yearsYup, and anything that needs jQuery. You would also need to run the code if jQuery is already defined.
-
Jeff almost 13 yearswould that equal to jQuery's onready event? Because we all hear preaches about writing event handlers in the ready event, right?
-
Jeff almost 13 years@gar-onn - I was referring to Stevens method :)
-
Jeff almost 13 yearsThis did it, thanks!! Also, this is the most painless solution of all :)
-
Adam Heath about 11 years@luqita Take a look at stackoverflow.com/questions/4845762/…
-
WWC almost 10 yearsThis one worked great for me! the "\x3C/Script>" portion when closing the script tag was the part that I needed. I tried document.write to write out the script tag, but the "</script>" was detected as a script closing tag even when in quotes.