jQuery plug-ins have few concrete rules, which is one of the
reasons for the incredible diversity in how they are implemented across
the community. At the most basic level, we can write a plug-in simply by
adding a new function property to jQueryâs jQuery.fn
object, as follows:
$
.
fn
.
myPluginName
=
function
()
{
// our plugin logic
};
This is great for compactness, but the following would be a better foundation to build on:
(
function
(
$
){
$
.
fn
.
myPluginName
=
function
()
{
// our plugin logic
};
})(
jQuery
);
Here, weâve wrapped our plug-in logic in an anonymous function. To
ensure that our use of the $
sign as a
shorthand creates no conflicts between jQuery and other JavaScript
libraries, we simply pass it to this closure, which maps it to the dollar
sign. This ensures that it canât be affected by anything outside of its
scope of execution.
An alternative way to write this pattern would be to use jQuery.extend()
, which enables us to define
multiple functions at once and sometimes make more sense
semantically:
(
function
(
$
){
$
.
extend
(
$
.
fn
,
{
myplugin
:
function
(){
// your plugin logic
}
});
})(
jQuery
);
We have now reviewed some jQuery plug-in fundamentals, but a lot more could be done to take this further. A Lightweight Start is the first complete plug-in design pattern weâll be exploring, and it covers some best practices that we can use for basic everyday plug-in development, taking into account common gotchas worth applying.
Note
While most of the patterns below will be explained, I recommend reading through the comments in the code, because they will offer more insight into why certain best practices are applied.
I should also mention that none of this would be possible without the previous work, input and advice of other members of the jQuery community. Iâve listed them inline with each pattern so you can read up on their individual work if interested.
Get Learning JavaScript Design Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.