Walking Through jQuery Plugin Boilerplate

jQuery BoilerplateBuilding jQuery plugins can be very fun and is done by many, many people today. The jQuery team has made it pretty darn easy to get up and running creating jQuery plugins, so much so that many JavaScript developers who don’t really know what they are doing jump onto the bandwagon too. This leads to horrible code floating around all over the internet. Thankfully, some very smart people came up with jQuery plugin boilerplates. Today I’ll walk you through one and show you how they make jQuery plugin coding simpler and more organized.

What is Boilerplate?

Boilerplate is code designed as a starting base for your code. jQuery boilerplate is JavaScript code that sets up all the code that is normally used in jQuery plugins. It also can solve some problems upfront that you wouldn't know would exist until you tried making a plugin without it.

Below you'll see an example of a boilerplate, which is available from jQuery Boilerplate (very original name). You can find different boilerplates all over the internet, including at Websanova, which is run by a friend of mine. Also, Addy Osmani has brought together a whole bunch of jQuery boilerplates from around the web so that you can choose the one you like.

// the semi-colon before function invocation is a safety net against concatenated 
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, undefined ) {

    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.

    // window and document are passed through as local variables rather than globals
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = 'defaultPluginName',
        document = window.document,
        defaults = {
            propertyName: "value"
        };

    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;

        // jQuery has an extend method which merges the contents of two or 
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype.init = function () {
        // Place initialization logic here
        // You already have access to the DOM element and the options via the instance, 
        // e.g., this.element and this.options
    };

    // A really lightweight plugin wrapper around the constructor, 
    // preventing against multiple instantiations
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
            }
        });
    }

}(jQuery, window));

Step by Step

Let's walk step by step through that code so I can help explain what it is, what it does, and why it's helpful. First, let's take a look at lines 3 and 53. Here we have an immediately invoked function expression (aka IIFE or, if you prefer, self-invoking anonymous function). This wraps the plugin code up so it's safe from outside tampering. Also it allows us to send in jQuery and shorten it to the $ without worrying about someone turning on noConflict. window and undefined were also used as parameter so that 1) we could use them without fear of tampering (especially in the case of undefined because in older versions of JavaScript, undefined was mutable) and 2) it allows us to shorten those references when the code is minified, but of course you already knew that because the comments in lines 5-12 told you so. If you noticed the semicolon before the opening parenthesis on line 3 and you're not sure what that's all about, just read the comments on lines 1 and 2.

Now let's take a look at lines 15-19. The first thing you should notice is that these variable are defined outside of any functions – the IIFE doesn't count – which limits the number of instances to 1 (as opposed to 1 for each time the plugin is called or a plugin object is instantiated) and it makes them available to everything within the IIFE. The first variable is pluginName, which should be the name of the function that you are extending jQuery with. It's referenced on lines 32, 45, 47, and 48. This allows you to change the name of your plugin in one place rather than in all 4 of those places mentioned (and more places if you need to reference it within the code you write). The next variable is document, which is just a reference to the document – often used in jQuery plugins – which allows it to be shortened by minifiers again. The final variable is defaults. Most plugins give users options that they can send in to the plugin and this variable contains the default values for each of the options you offer.

Let's move on to lines 22-35. This is the constructor for the object that will be doing all the heavy lifting in the plugin. The constructor is pretty minimal, mostly just creating a few instance properties and then leaving the rest up to init. Walking through, this.element holds the DOM element that this plugin is supposed to manipulate, this.options holds an object with all of the options that the user sent in and any defaults that weren't overridden by the user. The rest are pretty self-explanatory.

Now we are looking at lines 37-41. This is the init function where all the logic associated with this plugin's initialization should be placed. Personally, I would have written this part like this:

Plugin.prototype = {
    init: function() {
    
    }
}

This makes it so that you're set up to start adding additional methods to Plugin if you have them.

Finally we'll look at lines 45-51. This is where we actually extend jQuery with our plugin. As with just about any jQuery method, it returns this (actually this.each, which still returns this). This (pun not intended… if you can call it a pun) allows people to chain jQuery methods. Within each, we're checking to see if we've assigned a Plugin to the data of the DOM object. If we have, then we've got nothing to do for it because the plugin is already up and running there. If we haven't, the create a new Plugin object and add it to the DOM element's data.

A Walk to Remember

That about sums up this jQuery boilerplate code. It gets a lot of the basics done right away and gives you a bit of a framework to start building your code from. This, obviously, isn't the only approach to jQuery boilerplates. As stated on jqueryboilerplate.com, "Whilst the idea of a unique boilerplate is a great idea in theory, the reality is that in plugin development we rarely approach writing plugins in one very-fixed way using a single pattern all the time," meaning that this is not a one-size-fits-all solution and there are plenty of alternatives out there. I hope you've learned a bit and are excited to make your own jQuery plugins using an awesome boilerplate. Happy Coding!

About the Author

Author: Joe Zim

Joe Zim

Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.