May 26, 2017 Webby

Template-based Asset Munging in ExpressionEngine

In our years of working with ExpressionEngine, we’ve tweaked our standard setup quite a few times. We generally handle most every asset, including CSS and JavaScript, as a template. Being a bit obsessed with organization and overall maintainability of code, we separate out our styles and scripts into separate templates for each major concern (e.g. typography, color, screen layout, etc.).

A while back, it was not uncommon for us to include each of these assets into the document separately, but, as website optimization and performance folks will tell you, all of that separation leads to a lot of additional overhead because the browser must request each of those files individually. In the interest of streamlining the download process, we decided to merge all of the stylesheets together at the template level before sending them over the wire. Here’s the simple recipe we devised:

/* ———————————
* Core Stylesheet
* Created by Easy! Designs, LLC
* ——————————— */
@media screen
@media print
view rawmain.cssThis Gist brought to you by GitHub.

This framework allows us to pull in each template in the optimum way for progressive enhancement with only a single download on the user end, which is much faster. And server-side caching only adds to the speed improvements. Beyond that, we can continue to add new @media blocks (including media queries) as necessary either within the embedded files or in this master one.

We use a similar setup for our JavaScript:

/* Individual page handlers go here */
view rawmain.jsThis Gist brought to you by GitHub.

In this particular example, we’re including two jQuery plugins: FunctionHandler and hoverIntent, along with eCSStender before adding our page-specific code in FunctionHandler registrations. (jQuery itself is loaded in from Google.)

Using ExpressionEngine’s template system to manage the munging like this is dead simple and (from our experience evaluating other people’s EE setups) often underused. Give it a shot on your next project.