5
\$\begingroup\$

Please help me improve this function that compares the jQuery version currently available (or not) with the one required.

function(need) {
 if (typeof(jQuery) != 'undefined') {
 if (!need) return true;
 var re = /(\d+)\.(\d+)\.(\d+)/,
 cur = re.exec(jQuery.fn.jquery),
 need = re.exec(need);
 return (need[1] <= cur[1] && need[2] <= cur[2] && need[3] <= cur[3]);
 } else return false;
}
Zuul
5067 silver badges20 bronze badges
asked May 10, 2011 at 5:20
\$\endgroup\$

3 Answers 3

5
\$\begingroup\$

I'm sorry, but that code is completely broken.

  • It doesn't work if either version contains only two numbers such as the current "1.6".
  • It uses string comparison instead of integer comparison, so that it will return true if you "need" (theoretical) version "1.4.10" but only "1.4.2" is included, because "10" < "2" is true.
  • It doesn't stop comparing minor version numbers, if the major number is already bigger. For example it will return false if "1.4.2" is "needed", but "1.5.1" is included, because "2" > "1"
  • And finally you should keep in mind that "newer" isn't necessarily better. For example, the new 1.6 version changes how .attr() works, and scripts that rely on the old functionality of .attr() may break.
answered May 10, 2011 at 13:43
\$\endgroup\$
0
1
\$\begingroup\$

I just made a plugin.

$.versioncompare(version1[, version2 = jQuery.fn.jquery])

https://github.com/zuzara/jQuery-version-compare-plugin

answered Oct 27, 2011 at 5:46
\$\endgroup\$
-1
\$\begingroup\$

I feel like I'm missing something, but I got it down to one line for a compressed version, or a few lines for a verbose explination.

Compressed version:

(parseInt(jQuery.fn.jquery.split('.').join('')) > 140) ? alert("Running jquery greater than 1.4.0") : alert("current jquery version is 1.4.0 or less");

Long version for clarity:

// get version as a string and get rid of the periods. 
version = jQuery.fn.jquery.split('.').join('');
// Make into one long number for easy comparison. Example, 171, or 141.
version = parseInt(version);
if(version > 141){
 alert("We're using a version greater than 1.4.1");
}else{
 alert("jQuery version is 1.4.1 or lower");
}
Zuul
5067 silver badges20 bronze badges
answered Apr 26, 2012 at 23:10
\$\endgroup\$
1
  • \$\begingroup\$ Sorry, this is just as broken. It only works for two versions with the same number of parts and if those part only have 1 digit part. Examples: It will falsely conclude that "1.5" < "1.4.1" and "1.10" < "1.9". \$\endgroup\$ Commented Jul 11, 2012 at 15:03

You must log in to answer this question.