Reputation: 518
What's the best way of running a function depending on the version of jquery running? Right now I have:
var jqVersion = jQuery().jquery;
if (jqVersion == '1.4.2') {
//jQuery 1.4.2 specific script here.
} else {
//jQuery that works on rest of the site here
}
This works fine in Firefox, but in Chrome and IE the page gives an error for the code in the else
block even if the condition is met and the else
is unneeded. Cheers.
Upvotes: 2
Views: 365
Reputation: 707656
If your error is associated with .prop()
, that was added in jQuery version 1.6 then you should just check to see if that method is available and act accordingly.
if (jQuery().prop) {
// .prop() methods exists
}
or even just:
if (jQuery.fn.prop) {
// .prop() methods exists
}
FYI, you can see what version any given jQuery feature was added here.
My recommendation is to check to see if the specific method you want is there as above. But, if you feel you have to check versions, then you need to check greater than, not for equality. As you already know, jQuery().jQuery
contains the version as a string. If you want to check for a version greater than some number, then you need to parse that string into numbers and compare to them. Here's a function to do that:
jQuery.getVersionObject = function() {
var versionStr = jQuery().jQuery;
var matches = versionStr.match(/(\d+)\.(\d+)\.(\d+)/);
var num = (matches[1] * 1000 * 1000) + (matches[2] * 1000) + (matches[3]);
return ({major: matches[1], minor: matches[2], rev: matches[3]; num: num})
}
jQuery.checkMinVersion(major, minor, rev) {
minor = minor || 0;
rev = rev || 0;
var num = (major * 1000 * 1000) + (minor * 1000) + rev;
var version = jQuery.getVersionObject();
return(version.num >= num);
}
Example usage:
if (jQuery.checkMinVersion(1, 6, 0)) {
// jQuery version is 1.6.0 or higher
}
Upvotes: 2
Reputation: 160883
Do not write code depends on the jQuery version.
The most part of the code should be same, for some special part, test whether the property exists instead of using the version of jQuery.
Example:
if ('prop' in $jQueryObject) {
// do something
} else {
// do in other way
}
For using different version of jQuery in same page, check my answer of this question.
script reference causes conflict
Upvotes: 1