Inline CSS and JS in Hugo for better page performance

#misc #snippet

Inline CSS

Here is a trick of how to avoid the render blocking CSS file being loaded (and reported in Lighthouse) on your Hugo site. Inline the CSS using resources.Get function. The following example assumes that your CSS file is located in /assets/css/ directory.

{{ with resources.Get "css/styles.css" }}
    <style>{{ .Content | safeCSS }}</style>
{{ end }}

Inline and minify CSS

You can also minify the CSS content using the Hugo’s minify pipe. It removes the spaces & newlines.

{{ with resources.Get "css/styles.css" | minify }}
    <style>{{ .Content | safeCSS }}</style>
{{ end }}

Compile SCSS into CSS, inline and minify

Similarly, if you are using SASS on your Hugo site, use toCSS pipe. It compiles, minifies & inlines CSS.

{{ with resources.Get "css/styles.scss" | toCSS | minify }}
    <style>{{ .Content | safeCSS }}</style>
{{ end }}

Inline and minify JavaScript

You can also minify and inline Hugo’s JavaScript files. The following example assumes that your JS file is located in /assets/js/ directory.

{{ with resources.Get "js/main.js" | minify }}  
    <script>{{ .Content | safeJS }}</script>  
{{ end }}

These inline and minification techniques are currently in use on this site. You check the page source to see the inline CSS and JS. Also, check the Lightspeed report for this site - there are no render blocking assets.

⇐ All Blog Posts
Tweet Share