10 Tips for Developing Better jQuery Plugins

Share this article

There are some great jQuery plugins. The better ones are adopted by thousands of web developers throughout the world. Unfortunately, the worse ones fail and disappear into obscurity. Here are some tips to ensure your plugins reach their full potential…

1. Don’t Break the Chain

Unless your plugin returns a value, the last line of your plugin function must be:

return this;
this ensures method calls can be chained, e.g.

$("div#myid").yourPlugin().anotherPlugin().yetAnotherPlugin();

2. Make it Easy to Use

In most cases, your plugin should simply work without the developer having to wade though documentation, set options or edit your plugin code. If it’s a visual widget, the developer shouldn’t need to edit any JavaScript. You can simply provide HTML with a class/ID which will automatically launch your code, e.g.

<section class="myjqWidget">
<p>My content</p>
</section>
Your plugin can initialize itself, e.g.

$(function() {
		$("section.myjqWidget").myjqWidget();
});

3. Use Suitable Naming and Version Control Numbers

There are a lot of jQuery plugins. If you’re considering the name “tab” for your tab-handling plugin, there’s a strong possibility it’s been used already. That may not always matter but avoid using names which are ambiguous or likely to clash. Version numbering is also useful. It’s becomes especially important when developers report problems.

4. Use a Closure

Never depend on ‘$’ referencing jQuery. If the developer has another library installed, it may have grabbed it before jQuery was loaded. The simplest way to solve the issue is to pass jQuery as the ‘$’ argument for an anonymous self-starting function, e.g.

(function($) {
	// code here can use $ to reference jQuery
})(jQuery);

5. Set Default Parameters

Most plugins set parameters using JavaScript object literal notation, e.g.

$("#select").MyPlugin({opt1: 1, opt2: 2, opt3: "three"});
This has several advantages: parameters are easy to read, can be ordered in any way and omitted completely. However, you should set defaults within your plugin code and override them accordingly, e.g.

$.fn.PlugIn = function(opts) {
	// default configuration
	var config = $.extend({}, {
		opt1: 1,
		opt2: 2,
		opt3: 3,
		opt4: 4,
		opt5: 5
	}, opts);
Your plugin can then reference parameters using code such as config.opt1.

6. Support HTML Parameters

Ideally, HTML widgets should be able to set parameters without the developer needing to change JavaScript code. You could consider HTML5 data attributes, e.g.

<section class="myjqWidget" data-opt1="1" data-opt2="two">
<p>My content</p>
</section>
These can be accessed via jQuery’s data method: .data("opt1").

7. Document Your Code

Add concise comments to the top of your plugin which describe:
  • the plugin name and version
  • what the plugin does
  • example uses
  • the parameters
  • contact and support links
If it’s particularly complex, consider a separate readme file.

8. Test Your Plugin Thoroughly

Test it. Then test it again. In all browsers. There may be issues you’re not prepared to fix, e.g. IE6 compatibility problems. That’s fine, but ensure it’s mentioned within your documentation.

9. Use a Good Template

Here’s the template code I use when creating a new plugin:

/*!
 * jQuery plugin
 * What does it do
 */
(function($) {

	$.fn.PlugInName = function(opts) {
	
		// default configuration
		var config = $.extend({}, {
			opt1: null
		}, opts);
	
		// main function
		function DoSomething(e) {
		}

		// initialize every element
		this.each(function() {
			DoSomething($(this));
		});

		return this;
	};

	// start
	$(function() {
		$("#select").PlugInName();
	});

})(jQuery);
It provides a good starting point:
  • The plugin is wrapped in an enclosure.
  • It sets default options which are overridden by plugin parameters.
  • Each selected element is passed to the DoSomething function as a jQuery object.
  • return this; is included.
  • Auto-start code is provided at the end.

10. Get The Word Out

If you want developers to use your plugin, upload it to repositories such as GitHub, Google Code and jQuery Plugin directories. Create demonstration pages, publicize it in articles and tweet about it incessantly. Then be prepared to support the plugin and update it when necessary. You will receive dumb questions and bizarre feature requests, but that’s all part of being a successful plugin author. Do you have any top-tips for effective jQuery plugin development?

Frequently Asked Questions about jQuery Plugins Best Practices

What are the key considerations when creating a jQuery plugin?

When creating a jQuery plugin, it’s important to consider several factors. Firstly, ensure that your plugin is chainable. This means that it should return the jQuery object it was called on, allowing for multiple jQuery methods to be linked together. Secondly, provide default settings. This allows users to customize the plugin to their needs. Lastly, ensure your plugin is compatible with other plugins. This can be achieved by using the jQuery namespace to avoid conflicts with other plugins.

How can I make my jQuery plugin chainable?

To make your jQuery plugin chainable, you need to return the jQuery object it was called on. This allows for multiple jQuery methods to be linked together. Here’s an example of how to do this:

$.fn.myPlugin = function() {
// plugin code here
return this;
};

How can I provide default settings for my jQuery plugin?

You can provide default settings for your jQuery plugin by using the $.extend() method. This method merges two or more objects, creating a new object with the combined properties. Here’s an example:

$.fn.myPlugin = function(options) {
var settings = $.extend({
// default settings here
}, options);

// plugin code here
};

How can I ensure my jQuery plugin is compatible with other plugins?

You can ensure your jQuery plugin is compatible with other plugins by using the jQuery namespace. This helps to avoid conflicts with other plugins. Here’s an example:

(function($) {
$.fn.myPlugin = function() {
// plugin code here
};
})(jQuery);

What are some best practices for organizing jQuery code?

Organizing your jQuery code effectively can make it easier to read and maintain. Some best practices include: grouping related code into functions or objects, using meaningful names for variables and functions, and commenting your code to explain what it does.

How can I optimize my jQuery code for performance?

There are several ways to optimize your jQuery code for performance. One way is to cache jQuery objects. This means storing the result of a jQuery selection in a variable for later use. Another way is to use event delegation, which allows you to bind a single event listener to a parent element that will fire for all descendants matching a selector.

How can I handle errors in my jQuery plugin?

You can handle errors in your jQuery plugin by using the try...catch statement. This allows you to “catch” errors and handle them gracefully, rather than letting the script fail.

How can I test my jQuery plugin?

You can test your jQuery plugin by using a JavaScript testing framework like Jasmine or Mocha. These frameworks allow you to write test cases for your plugin and run them to ensure it works as expected.

How can I make my jQuery plugin accessible?

You can make your jQuery plugin accessible by following the Web Content Accessibility Guidelines (WCAG). This includes providing alternative text for images, ensuring your plugin can be used with a keyboard, and making sure it works with screen readers.

How can I distribute my jQuery plugin?

You can distribute your jQuery plugin by hosting it on a platform like GitHub. This allows others to download and use your plugin. You can also submit it to the jQuery Plugin Registry, which is a directory of jQuery plugins.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

HTML5 Dev CenterHTML5 Tutorials & ArticlesjavascriptjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form