jQuery: 3 plugin design principles

jQuery's design is based on simplicity, so the first principle of jQuery plugin design is simplicity. You should focus on simplicity. Nobody uses a plugin that is too complicated, so the golden rule is to keep things atomic. To accomplish this, you should keep the inner complexity hidden from a user's eye.

For example, instead of defining another option to perform a task, keep it secret by using a private function inside the main plugin body if this task doesn't involve a user's choice. Remember that inside a plugin you're actually working with a namespace that is known only to the jQuery library. When you use fn, you're inside a sandbox that prevents your code from polluting the global namespace.

Many plugins use private functions, but only a few of them use an object-oriented approach by defining private objects within the plugin body. Apparently, an OO approach increases the complexity level, but this is only an impression. The fact is that as long as a procedural approach involves the use of two or three functions, then everything works fine. But when the number of tasks increases, then maintaining your code may become cumbersome.

So here's the second principle: use OOP whenever it's possible. If you think carefully about a jQuery plugin, you will soon notice that OOP is used to define your plugin options. But the $.extend() method can be used to extend all your objects, not only your plugin options. You can then create two kind of settings, one private and one public. Your private settings will be used by the plugin for its core working, whereas the public settings will be used by the plugin user.

Objects are a lot neater than defining a long list of variables. Suppose that you have to perform some kind of browser detection because you've noticed that your plugin works differently in some browsers. In your private settings, you can define a private method to accomplish this:

$.fn.myPlugin = function(options) {

  var coreOptions = {
    isBrowserX: function() {
      // browser detection code
      return false;


options is a public object, while coreOptions will be used only by the plugin and doesn't require user interaction.

Finally, the third principle is the cornerstone of every successful jQuery plugin: specificity. Your plugin should perform a specific task, the kind of task that most developers need when they search a plugin on the web or when they post a message on a mailing list or forum. There are dozens of jQuery sliders, so if you want to create another one, choose a feature that other sliders don't have, for example a full screen jQuery slider to create presentation effects.

Even better, you should choose a field where there is a desperate need for a jQuery plugin. This will surely help your plugin to be successful.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.