Skip to content

Instantly share code, notes, and snippets.

@willbuilds
Last active May 3, 2021 00:51
Show Gist options
  • Save willbuilds/d2065346592eb3929147dbeca342f64c to your computer and use it in GitHub Desktop.
Save willbuilds/d2065346592eb3929147dbeca342f64c to your computer and use it in GitHub Desktop.
{% comment %}
Use this snippet to add a responsive image to page.
Requires lazysizes.js
Specify Shopify image you want to make responsive in the "with" parameter (see examples below).
You can use following variables to customize the image
* type: specifies the type of image file being accessed (ie an image from content, a product image, or a theme asset image).
* default_size: size of placeholder image until full image is loaded (default: '150x')
* class: additional classes to be applied to an image
* alt: alt text for the image
* props: additional properties for the <img /> tag (data-, styles, id, etc.)
Usage:
* Define variables inside the include tag (preferred):
{% include 'responsive-image' with product.image, class: 'product-image', alt: 'A simple product', default_size: '300x', props: 'data-id="1"' %}
* Define variables before including this snippet
{% assign class = "product-image" %}
{% assign alt = "A simple product" %}
{% assign default_size = '300x' %}
{% capture props %}
data-id="1"
{% endcapture %}
{% include 'responsive-image' with product.image %}
{% endcomment %}
{% if default_size == blank %}
{% assign default_size = '150x' %}
{% endif %}
{% case type %}
{% when blank or 'img' %}
{% assign lo_res_url = responsive-image | img_url: default_size %}
{% assign responsive_url = responsive-image | img_url: '1x1' | replace: '_1x1.', '_{width}x.' %}
{% assign fallback_url = responsive-image | img_url: '1000x1000' %}
{% when 'asset' %
{% assign lo_res_url = responsive-image | asset_img_url: default_size %}
{% assign responsive_url = responsive-image | asset_img_url: '1x1' | replace: '_1x1.', '_{width}x.' %}
{% assign fallback_url = responsive-image | asset_img_url: '1000x1000' %}
{% when 'file' %}
{% assign lo_res_url = responsive-image | file_img_url: default_size %}
{% assign responsive_url = responsive-image | file_img_url: '1x1' | replace: '_1x1.', '_{width}x.' %}
{% assign fallback_url = responsive-image | file_img_url: '1000x1000' %}
{% endcase %}
<noscript>
<img
class="responsive-image {{ class }}"
src="{{ fallback_url }}"
data-sizes="auto"
{% if alt %}
alt="{{ alt | escape }}"
{% endif %}
{{ props }}
/>
</noscript>
<img
class="lazyload responsive-image {{ class }}"
src="{{ lo_res_url }}"
data-src="{{ responsive_url }}"
data-sizes="auto"
data-aspectratio="{{ responsive-image.aspect_ratio }}"
{% if alt %}
alt="{{ alt | escape }}"
{% endif %}
{{ props }}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment