jQuery version compatibility detection

前端 未结 6 717
刺人心
刺人心 2020-12-09 13:38

Are there any resources that can test a jQuery script/extension/plugin/whatever for version compatibility issues?

6条回答
  •  旧时难觅i
    2020-12-09 13:50

    Here's my quick and dirty solution:

    var versionGTE = function (valueA, valueB) {
      var values = [valueA, valueB];
      values.sort();
      // if valueA > valueB, values will have switched
      return (values[1] === valueA);
    };
    

    Example usage:

    if (versionGTE(jQuery.fn.jquery, "1.3")) {
      // don't use @ in attr selectors
    }
    

    It does an alphabetical sort on the array. The only time it fails is if for some reason the version "x.y" vs "x.y.0". In that case the .0 version is perceived as being greater. It doesn't support "pre" versions either.

    Here's a smaller version:

    var versionGTE = function (valueA, valueB) {
      return ([valueA, valueB].sort()[1] === valueA);
    };
    

    Here's a more reliable function if you're worried about "rc1", "pre", or x.0 versions:

    var versionCompare = function (versionStringA, versionStringB) {
      // quick test of equality before digging in
      if (versionStringA === versionStringB) return 0;
    
      var versionedAlpha = /[a-z]+(\d+)/gi,
          getArray = function (verString) {
            // replace rc1, rc2, beta3, etc with .-1.1, .-1.2, .-1.3, etc
            return verString.replace(versionedAlpha, ".-1.$1").split(".");
          },
          valuesA = getArray(versionStringA),
          valuesB = getArray(versionStringB),
          maxLength = Math.max(valuesA.length, valuesB.length),
          hasLetters = /[a-z]/gi,
          // assume any version with letters is -1 (pre, rc, etc)
          // also assume that any null entries are 0 (1.5 === 1.5.0)
          parseVersion = function (verString) {
            return (verString) ? (hasLetters.test(verString)) ? -1 : parseInt(verString, 10) : 0;
          };
    
      // verify both arrays are the same size
      valuesA.length = maxLength;
      valuesB.length = maxLength;
    
      for (var i = 0; i < maxLength; i++) {
        var valueA = parseVersion(valuesA[i]),
            valueB = parseVersion(valuesB[i]);
    
        if (valueA < valueB) {
          return -1;
        } else if (valueA > valueB) {
          return 1;
        }
      }
    
      // all equal at this point
      return 0;
    };
    

    This is like a sort or .compare function in that it will return 0 if equal, 1 if a > b, and -1 if a < b. Example:

    if (versionCompare(jQuery.fn.jquery, "1.3") >= 0) {
      // don't use @ in attr selectors
    }
    

提交回复
热议问题