Skip to content

jQuery plugin design recommendations

Reference: Learning jQuery (Fourth Edition), Chapter 8

Protect the dollar ()aliasfrompotentialinterferencefromotherlibrariesbyusingjQueryinssteadorpassing into an immediately invoked frunction expression (IIFE), so that it can be used as a local variable.

Whether extending the jQuery object with .myPluginorthejQueryprototypewith.fn.myPlugin, add no more than one property to the namespace.Additionalpublicmethodsandpropertiesshouldbeaddedtothepluginsnamespace(forexample,.myPlugin.publicMethod or $.fn.myPlugin.pluginProperty).

Provide and object containing default options for the plugin: $.fn.myPlugin.defaults = {size: 'large'}.

Allow the plugin user to optionally override any of the default settings for all subsequent calls to the method (.fn.myPlugin.defaults.size=medium;)orforasinglecall(('div').myPlugin({size: 'small'});).

In most cases when extending the jQuery prototype .fn.myPlugin,returnthistoallowallowthepluginusertochainadditionaljQuerymethodstoit(forexample,('div').myPlugin().find('p').addClass('foo')).

When extending the jQuery prototype ($.fn.myPlugin), enforce implicit iteration by calling this.each().

Employ callback functions when appropriate to allow for flexible modification of the plugin's behavior without having to change the plugin's code.

If the plugin calls for user interface elements or needs to track elements' state, create it with the jQuery UI widget factory.

Maintain a set of automated unit tests for the plugin with a testing framework such as QUnit to ensure that it works as expected.

Use a version control system such as Git to track revisions to the code. Consider hosting the plugin publicly on GitHub (http://github.com/) and allowing others to contribute.

If making the plugin available for others to use, make the licensing ters clear. Consider using the MIT license, which jQuery also uses.

天上的神明与星辰,人间的艺术和真纯,我们所敬畏和热爱的,莫过于此。