jQuery Plugins - Prevent Multiple Instantiations

##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
1
2
3
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
1
2
3
4
5
6
7
<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.

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

Attachment Check
1
2
3
4
5
6
7
8
9
10
11
(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 attach itself to the jQuery object.