Validating if a jQuery plugin exists before running code that use it

jquery-logo

When we are creating plugins or simple code in jQuery and there is a single or many plugin dependences among them, a common task is to implement a mechanism to validate if a jQuery plugin exists before running “depending” code, for example if we have this code and we have not included jqprint (a nice plugin to print a fragment of an HTML document), then an error will appear indicating that jqprint function is undefined.

(function($) {
    $(document).ready(function() {
        $(".print-this-section").on('click', function(){
            $("#section-to-print").jqprint();
        });
    });
})(jQuery);

So, in order to solve this “undefined” error we could add a little validation before running jqprint code.

(function($) {
    $(document).ready(function() {
 		if( jQuery().jqprint ){ // Verifying jqprint exists
	        $(".print-this-section").on('click', function(){
	            $("#section-to-print").jqprint();
	        });
		}
    });
})(jQuery);

With this simple code, you would be able to avoid errors in your code when a plugin is not defined.

That’s it!

Be happy with your code!

Alex Arriaga

Leave a Reply

Your email address will not be published. Required fields are marked *