This post will show you how to check currently loaded jQuery version on the page. This maybe useful in your jQuery plugins, in cases when your code utilizes jQuery version specific methods. Also, when you are writing code that runs in an environment where jQuery is already embedded. For example in open source CMS's like Drupal, Magento Ecommerce, etc.
jQuery keeps track of the current version of the script being used in jQuery.fn.jquery
property. Both major version version 1.x and version 2.x have this property.
// Returns string: "1.10.2"
jQuery.fn.jquery;
// Since jQuery == $, we can use shorthand syntax
$.fn.jquery;
You can look into the jQuery source code and find out that jQuery.fn
is a reference to jQuery.prototype
.
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
...
This means we can use alternative method to get current jQuery version like so:
// Alternative method, also returns string
jQuery().jquery;
// or shorthand method
$().jquery
Caveats & notes
I would like to remind you that jQuery must be loaded before you call the code above. Otherwise, it will throw an error: ReferenceError: jQuery is not defined
or TypeError: $(...) is null
. To avoid it, you can check for existance of jQuery first.
if (window.jQuery) {
jQuery().jquery;
}
If jQuery is not loaded, we can load it dynamically from an alternative location.
if (!window.jQuery) {
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.src = '/path-to-your/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
Also, learn how to check loaded jQuery UI version.