Shopify: Liquid Snippet for Loading CSS Asynchronously

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:

Sectionlocationindex
Announcement bannerheader1
Nav barheader2
Static sectionstaticnil
Image with texttemplate1
Another image with texttemplate2
Featured articlestemplate3
Footerfooter1
comments powered by Disqus