Sublayout Driven JavaScript In Sitecore

A pragmatic JavaScript technique for Sitecore

Problem

Using <script> tags inline? Does every page load all the JavaScript for entire site? Losing track of what JavaScript is doing what where? These are common scenarios. The relatiopnship in Sitecore between Layouts and Sublayouts makes it challenging to deal elegantly with JavaScript.

We've all seen a Sitecore Layout that looks like this:

Excessive JavaScript In The Layout

All that JavaScript haphazardly loaded on every single page. This results in extra bandwidth, slower page execution (syncrohnous JS is blocking) and ever increasing page complexity.

"You clicked where? Then what happened? No problem. Just let me comb through the 100 JavaScript files on our page to see what caused that."

If that sounds familiar, I'd suggest a different approach.

Solution

Make your Sublayouts add the JavaScript they require. Simple.

Change Our Layout

In your Layout, add a Literal control (acting as a placeholder) where you would like your JavaScript to be injected. If you load your JS syncronously, you may want to move the placeholder to the bottom of the Layout.

Modified Layout with a PlaceHolder for JavaScript

Write The Code

Here is an implementation of the AddJS() method we use.

Class containing overloaded AddJS() method

We'll use this from the Sublayout (next step). It's implemented as an overloaded static method. Pass in the path to your JavaScript and any attributes you'd like to include.

Implementation

This shows a "HomePage" Sublayout that requires 3 JavaScript files. See the different ways the method can be used to add JavaScript.

Calling AddJS() from a Sublayout

The first example with attributes is the most noteworthy. A data attribute is used to indicate which Sublayout loaded each JavaScript. This adds further clarity for items that have many Sublayouts.

Closing Thoughts

This technique really becomes powerful when combined with AMD Loaders (e.g. RequireJS) in Sitecore. They allow you to load a single JS file and have all its dependencies loaded on demand, asyncronously. We hope to write about using RequreJS in the near future.

Caveat

This technique will not work with Sublayout caching enabled. Because Sitecore caches the rendered HTML, the C# Page_Load() method is only executed on the first visit.

That said, it can also be act as a reminder to keep your Sublayouts lean and push expensive data requests asyncronohously to the client-side. Thanks for reading!

Fish