Google Page Speed Tips - Part 2 - Defer & Async Inline JavaScript

This post includes a couple of techniques for optimizing the JavaScript loaded by your Templates & Pages. These help with Above the Fold content warnings.

In order to optimize Page Speed we want to ultimately defer or async load JavaScript referenced by the published Page. This includes snippets provided by 3rd parties, snippets in custom widgets, HTML widgets or included in the Additional Content section of a Page or Template’s metadata.

async or defer
The <script> tag supports two attributes that tell the browser how the script block should be processed. With neither attribute supplied the script tag will be process in the order it shows up in the document.

async should generally be used for any scripts that are stand alone and don’t necessarily affect the look and feel of a Page. Good candidates for the async attribute are snippets from Analytics providers like Google or Siteimprove. Simply adding the async attribute to these script blocks will tell the browser to load them asynchronously (in any order) and not to block loading / downloading the rest of the page.

defer should be used for scripts that can load after the main content of the Page has been download by the web browser. Generally this can be used for all inline scripts and JavaScript files. This post covers JavaScript added to templates through the Additional Head content or in inline scripts. Part 3 will cover the JavaScript references added by the CM1 system.

When looking at scripts in the Metadata → Additional Content section.

  • Move any script references to the Before Body Close block. This puts the scripts Below the Fold.
  • Leave any CSS references in the Additional Head Content.
  • Add the “defer” attribute to each external script reference.
  • Update inline JavaScript to be wrapped by the DOMContentLoaded event function.

Wrapping Inline JavaScript
Inline JavaScript script tags ignore the defer or async attribute, so for inline JavaScript blocks we want to wrap the existing script so that it is triggered to run when the DOMContentLoaded event is fired.

An example of this is below.

<script>
    window.addEventListener('DOMContentLoaded', function() { 
    ...
    });
</script>

You should check all Custom Widgets, HTML Widgets, or Rich Text widgets to make sure that any inline JavaScript is wrapped in this fashion. jQuery Document Ready events will still fire, just not til after the browser has downloaded the main content, which is what Google Page Speed is looking for.

All Percussion Widgets will defer inline JavaScript as part of the 5.4 release.