Skip to content

Instantly share code, notes, and snippets.

@leofavre
Last active May 19, 2019 06:12
Show Gist options
  • Save leofavre/8983577f388e296776c937c7699a4ec6 to your computer and use it in GitHub Desktop.
Save leofavre/8983577f388e296776c937c7699a4ec6 to your computer and use it in GitHub Desktop.
Using srcset and sizes for product imagens on Shopify without Javascript (if you know their aspect ratio)
{% comment %}
If all product images of your Shopify store share the same aspect ratio,
you can use the following snippet to generate the correct srcset without
having to use Javascript to detect their widths.
The aspect ratio of an image is equal to its width divided by its height.
Example: for an image that is 1536px wide by 2048px tall,
the aspect ratio will be 1536 / 2048 = 0.75;
The `default` variable corresponds to the default size that older browsers
that do not understand the srcset attribute will use.
The `sizes` variable correspond to the sizes attribute, which will depend
on your lay-out and your CSS.
{% endcomment %}
{% assign image = product.featured_image %}
{% assign ratio = 0.75 %}
{% assign default = 'grande' %}
{% assign sizes = '(min-width: 1360px) 650px, 45vw' %}
<img src="{{ image | product_img_url: default }}"
srcset="
{{ image | product_img_url: 'pico' }} {% if ratio < 1 %}{{ 16 | times: ratio | round }}{% else %}16{% endif %}w,
{{ image | product_img_url: 'icon' }} {% if ratio < 1 %}{{ 32 | times: ratio | round }}{% else %}32{% endif %}w,
{{ image | product_img_url: 'thumb' }} {% if ratio < 1 %}{{ 50 | times: ratio | round }}{% else %}50{% endif %}w,
{{ image | product_img_url: 'small' }} {% if ratio < 1 %}{{ 100 | times: ratio | round }}{% else %}100{% endif %}w,
{{ image | product_img_url: 'compact' }} {% if ratio < 1 %}{{ 160 | times: ratio | round }}{% else %}160{% endif %}w,
{{ image | product_img_url: 'medium' }} {% if ratio < 1 %}{{ 240 | times: ratio | round }}{% else %}240{% endif %}w,
{{ image | product_img_url: 'large' }} {% if ratio < 1 %}{{ 480 | times: ratio | round }}{% else %}480{% endif %}w,
{{ image | product_img_url: 'grande' }} {% if ratio < 1 %}{{ 600 | times: ratio | round }}{% else %}600{% endif %}w,
{{ image | product_img_url: '1024x1024' }} {% if ratio < 1 %}{{ 1024 | times: ratio | round }}{% else %}1024{% endif %}w,
{{ image | product_img_url: '2048x2048' }} {% if ratio < 1 %}{{ 2048 | times: ratio | round }}{% else %}2048{% endif %}w
"
sizes="{{ sizes }}"
alt="{{ image.alt | escape }}"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment