Thursday, July 3rd, 2008

JavaScript Plugins; The beauty of loosely coupled code

Category: JavaScript

James Coglan wrote a piece on There is no such thing as a JavaScript plugin that uses jQuery as a use case for how simple it is to have a plugin contract.

When you think about plugins in many environments, you have strict contracts through interfaces that you have to implement. With jQuery, you can just add on to the jQuery prototype, normally seen through the alias $.fn.

James shows the simple example of:


  1. $.fn.makeThemRed = function() {
  2.   this.css({color: 'red'});
  3.   return this;
  4. };
  6. $('p').makeThemRed();

I read this as the power of the simplicity, but John Resig, again in his three parter saw it a little different, I think by thinking too much about the title :)

I will contend that such a thing as plugins exist and are logically distinct from “random JavaScript code that manipulates other JavaScript code” as long as the following points are met:

  1. There have to be explicit points upon which a plugin can attach. James notes the most common one in jQuery (jQuery.fn) but we have tons more – events, animations, selectors – all over the board for developers to snap in to.
  2. Even more importantly: Those points have to be documented or, at the very least, be under some sort of agreement that they will be treated like a normal piece of the user-facing API. In jQuery we treat all plugin extension points as “user-facing API” and only ever change them in major releases (if at all) and always provide an alternative for authors to use.
  3. Finally, there has to be some sort of repository for navigating these plugins. This is a huge differentiator. Simply referring to “code in the wild” as plugins doesn’t really cut it if there’s no commitment to hosting them and keeping their documentation and examples alive.

Posted by Dion Almaer at 10:16 am

3.5 rating from 23 votes


Comments feed TrackBack URI

the only thing I’m not too thrilled about is the lack of namespacing for jquery plugins…

Let’s say you develop an autocomplete plugin and i develop and autocomplete plugin…

i can’t use the different implementations on the same page.

i tried briefly to get around this in jquery, but gave up. Any suggestions?

Comment by ilazarte — July 3, 2008

I still don’t see what the big fuss is. $.fn is just the prototype — that is common to all JavaScript.


Maybe I misunderstood where the praise was going, but the praise should go to JavaScript for being prototypal and referencing Objects.

Comment by ibolmo — July 6, 2008

Leave a comment

You must be logged in to post a comment.