Shopify: Liquid Snippet for Loading CSS Asynchronously
18 October 2023
·
19 October 2023
2 minutes
18 October 2023 · 2 minutes
Shopify: Liquid Snippet for Loading CSS Asynchronously
Shopify recently added section.index to the Liquid API. This is a great addition that allows you to do things like selectively load CSS based on the section index. This is useful for things like loading CSS asynchronously, which can help improve your page speed scores. If you want to load CSS asynchronously on Shopify, you can use this Liquid snippet: css.liquid {%- liquid assign css = css | default: false assign section_index = section_index | default: 3 -%} {%- if section_index > 2 -%} <link rel="stylesheet" href="{{- css | asset_url-}}" media="print" onload="this.
Shopify recently added section.index to the Liquid API. This is a great addition that allows you to do things like selectively load CSS based on the section index. This is useful for things like loading CSS asynchronously, which can help improve your page speed scores.
If you want to load CSS asynchronously on Shopify, you can use this Liquid snippet:
css.liquid
{%- liquid
assign css = css | default: false
assign section_index = section_index | default: 3
-%}
{%- if section_index > 2 -%}
<link rel="stylesheet" href="{{- css | asset_url-}}" media="print" onload="this.media='all'">
<noscript>
{{- css | asset_url | stylesheet_tag -}}
</noscript>
{%- else -%}
{{- css | asset_url | stylesheet_tag -}}
{%- endif -%}
Then, you can render this snippet in your theme with this code:
{%- render 'css', css: 'example.css', section_index: section.index -%}
With using this snippet, you can load CSS asynchronously for sections and limit it to sections further down the page so that it does not impact Cumulative Layout Shift (CLS).
Note:
You should define custom section_index value for static sections in this snippet, because Shopify does not set section_index value for static sections. You can define this value as 1 for top static sections, 3 for bottom static sections.
Here is a table of the default section_index values for each section type:
Section | location | index |
---|---|---|
Announcement banner | header | 1 |
Nav bar | header | 2 |
Static section | static | nil |
Image with text | template | 1 |
Another image with text | template | 2 |
Featured articles | template | 3 |
Footer | footer | 1 |