A Lightweight Start Pattern
Let’s begin our deeper look at plug-in patterns with something basic that follows best practices (including those in the jQuery plug-in authoring guide). This pattern is ideal for developers who are either new to plug-in development or who just want to achieve something simple (such as a utility plug-in). A Lightweight start uses the following:
Common best practices such as a semicolon placed before the function’s invocation (we’ll go through why in the comments below).
window,document, andundefinedpassed in as arguments.A basic defaults object.
A simple plug-in constructor for logic related to the initial creation and the assignment of the element to work with.
Extending the options with defaults.
A lightweight wrapper around the constructor, which helps to avoid issues such as multiple instantiations.
Adherence to the jQuery core style guidelines for maximized readability.
/*!* jQuery lightweight plugin boilerplate* Original author: @ajpiano* Further changes, comments: @addyosmani* Licensed under the MIT license*/// the semi-colon before the function invocation is a safety// net against concatenated scripts and/or other plug-ins// that are not closed properly.;(function($,window,document,undefined){// undefined is used here as the undefined global// variable in ECMAScript 3 and is mutable (i.e. it can// be changed by someone else). undefined isn't really// being passed in so we can ensure that its value is// truly undefined. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access