jQuery Plugins - Prevent Multiple Instantiations

06/03/2014, Tue
Categories: #JavaScript
Tags: #jQuery

Script Loading Safety

The jQuery Boilerplate is a popular boilerplate and provides a safety net for double instantiation of a jQuery object with this code

// Prevent Double Instantation on jQuery Object

if (!$.data(this, "plugin_" + pluginName)) {
  $.data(this, "plugin_" + pluginName, new Plugin(this, options));
}

This is good safeguard for your jQuery objects, but what happens if your plugin script gets load twice?

<!-- Accidental Reloading of Plugin Script-->

<head>
  <title>TakeOut</title>
  <meta charset="UTF-8" />
  <script
    src="assets/vendor/js/jquery-1.11.1.min.js"
    type="text/javascript"
  ></script>
  <script src="src/TakeOut.js" type="text/javascript"></script>
  <script src="src/TakeOut.js" type="text/javascript"></script>
</head>

This is unlikely to happen, but this problem could manifest in more devious or and less apparent ways, such as when project files are minify and concatenated.

It might cause some unexpected behaviors if the plugin attaches event listeners by default. In order to protect your page, do the following:

// Attachment Check

(function ($, window, document, undefined) {
  var pluginName = "MyMagnificentJQueryPlugin";

  // Only allow for one instantiation of this script
  if (typeof $.fn[pluginName] !== "undefined") {
    return;
  }

  // Rest of your jQuery plugin logic here
})(jQuery, window, document);

There is a check in the beginning of the script to see if the plugin has already attached itself to the jQuery object.