jQuery: conditional code based on the jQuery's version

jQuery: conditional code based on the jQuery's version

We can take advantage of the inner jQuery version string in order to write conditional code.

We can take advantage of the inner jQuery version string in order to write conditional code.

The following utility function simply splits the jQuery's version string into its main components and allows users to perform a comparison by returning a Promise:


(function( $ ) {
   $.versionCompare = function( compareFn ) {
       var jqueryVer = jQuery.fn.jquery;
       var jqueryVerparts = jqueryVer.split( "." );
       var parts = {
           major: parseInt( jqueryVerparts[0], 10 ),
           minor: parseInt( jqueryVerparts[1], 10 ),
           branch: parseInt( jqueryVerparts[2], 10 )
       };

       return new Promise(function( resolve, reject ) {
           if( compareFn( parts ) ) {
               resolve( parts );
           } else {
               reject( Error( "jQuery version does not match" ) );
           }
       });

   };
})( jQuery );

Example:


$(function() {
    $.versionCompare(function( data ) { return data.major > 2 }).then(function( result ) {
        // Our code goes here
    }).catch(function( err ) {
        // Error handling
    });
});

In this particular case our code will be executed only if the major version of jQuery is greater than 2.