JQuery AMD Plugin Template

06 Aug 2013

Several years ago I posted how to write a jquery plugin template, but in the recent years, browser javascript is evolving, developers are more likely using asynchronous module definition API (Require.js). So the jquery plugin template should also be updated like

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as anonymous module.
    define(['jquery'], factory);
  } else {
    // Browser globals.
}(function ($) {
  $.fn.pluginName = function(options) {
    var defaults = {
      // define default options

    var o = $.extend({}, defaults, options);

    return this.each(function() {
      var e = $(this);
      // write logic here

The difference is the jquery plugin uses asynchronous jquery module if it exists, otherwise uses global jQuery as usual.


blog comments powered by Disqus