SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

IIFE Plugin Wrapper

IIFE Wrapper

Wrap plugins in an Immediately Invoked Function Expression (IIFE) to protect the $ alias and avoid polluting the global scope.

Example
;(function($, window, document, undefined) {
  "use strict";

  $.fn.myPlugin = function(options) {
    const defaults = { color: "red", speed: 400 };
    const settings = $.extend({}, defaults, options);

    return this.each(function() {
      $(this).css("color", settings.color)
             .fadeIn(settings.speed);
    });
  };

}(jQuery, window, document));
Pro Tip

The leading semicolon prevents issues when concatenating scripts that lack trailing semicolons.