Plugin development: $.fn.pluginName vs $.pluginName
Hi all,
I've been wondering about something for a while now and hopefully
other jquery developers can shed their light of ideas on it as well.
When creating plugins, there are generally 2 places where people plug
into the jquery library.
$.pluginName = { /* plugin code */ }
and
$.fn.pluginName = { /* plugin code */ }
While there's quite a difference, I've noticed that people inject into
the latter without any thought and thereby 'polute' the jquery
prototype, which is duplicated on each $(myJQueryQuery) call. Right? I
am not very familiar with the JS Engine insides, but the way I
understand it, on every call to jQuery the complete $.fn part is
duplicated and therefore reduces performance as a whole.
For this specific reason, I've recently created a plugin with the
following pattern:
$.fn.pluginName = function(options) {
$.pluginName.init($.extend({mySelf: this}, $.ajaxNav.pluginName,
options));
};
$.ajaxNav = {
defaults: {
...
},
cache: [],
init: function(options) {
options.cacheIndex = this.cache.length;
this.cache[options.cacheIndex] = settings;
// Do init stuff and store in options
this.someFunction(options);
},
someFunction(options) {
// Stuff to do in another function
}
}
This way, we keep the $.fn space clean and only add to the _once_ per
page initialised jQuery namespace.
Using the options parameter which is passed to every called function
we know which instance we're dealing with, and for general events (do
stuff on window resize?) we have the $.pluginName.cache to find all
our instances in (and the ones which have a flag for a specific Event,
for instance, will be triggered => saves on event binds as well!).
Maybe I'm getting it all wrong is my pattern rediculous for this and
this reason, or perhaps lots of plugins I'm not aware of are already
using this, but AFAIK many large plugins pollute the $.fn space quite
badly and AFAIK this will impact performance (jQuery is instantiated A
LOT in the average website) unnecessarily.
If not convinced, run "console.log($(document))" on your average
jQuery powered website and check the DOM inspector.
Any thoughts are welcome! I hope there will be some feedback from
anyone having an opinion on this matter.
Cheers,
Yereth