Scope Issues with the Sitecore Page Editor and IIFE

January 7, 2015

The JavaScript IIFE (Immediately-Invoked Function Expression) pattern is awesome and has many benefits like privately scoping your variables. The basic IIFE looks like this:

(function(){
  /* code */ 
}());

Simply replace /* code /* with your custom JavaScript to enjoy the benefits of an IIFE. JavaScript code in this format will work just fine in the Sitecore Page Editor.

The Problem

However, you often see examples of IIFEs using a format similar to:

(function($){
  /* code */ 
}(jQuery));

Passing jQuery as a parameter to your IIFE will cause issues when running your site in the Sitecore Page Editor. You will get Uncaught TypeError: undefined is not a function errors in the console when you call a method defined in the IIFE.

The reason this causes an issue is because the Sitecore Page Editor injects it's own version of jQuery into the page. When you pass jQuery as a parameter to your IIFE it will scope it to just one version. If your calling code is not using that version of jQuery, the method will be undefined.

Summary

The simplest solution is to remove jQuery as a parameter to your IIFE. This may not be possible in all situations, but should work for the majority of front end Sitecore development.

References

For a more detailed discussion on the pros/cons of IIFE parameters see: