We recently had some clients who wanted to get more speed out of HubSpot, but after going through our usual image optimization techniques and concatenating files they still weren't satisfied. We dug around and found out we could load CSS files asynchronously so that page rendering isn't blocked while the stylesheet loads. Here's how to do it:
- Load the stylesheet like this:
<link rel="preload" href="link-to-stylesheet-here" as="style" onload="this.onload=null;this.rel='stylesheet'"/>
- You'll notice the link tag uses some JavaScript to change the rel to stylesheet on load, so you need to use this code as a backup for when JavaScript is disabled:
<noscript><link rel="stylesheet" href="link-to-stylesheet-here"></noscript>
- Next, copy the LoadCSS script from here and inline it in a script tag right below the link and noscript tags like this:
<script>
/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
(function(){ ... }());
</script> - Remove the stylesheet from HubSpot's internal linking tool (check both content settings and the template for this) so the stylesheet isn't loading twice.
- Use this tool to get the critical CSS for the above the fold content, and inline that CSS in a style tag at either template or page level. The tool isn't perfect and seems to include extra CSS from below the fold, but if you don't want to gather that CSS yourself it'll get the job done.
- Make sure your inline CSS is minified. Try minifier.org.
- The final result will look like this:
<link rel="preload" href="link-to-stylesheet-here" as="style" onload="this.onload=null;this.rel='stylesheet'"/>
<noscript><link rel="stylesheet" href="link-to-stylesheet-here"></noscript>
<script> /*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */ (function(){ ... }()); </script>
LoadCSS is a polyfill that allows us to load CSS asynchronously across all browsers. You can find the documentation here.