JekyllConf: Responsive images with Jekyll

How to implement responsive images with Jekyll and imgix (video and notes from my lightning talk).

This project was originally completed .

This writing was last updated 2016-05-09.

Static websites built with tools like Jekyll are fast by their nature. With quickly served static assets (like HTML documents, scripts, images, and stylesheets) there is not much overhead in hosting a static site.

Images are often the heaviest resources on static sites and are a great place to start when improving front-end performance. According to the HTTP Archive, 63.5% of the average page’s weight was made up of images (as of April 2016). With srcset (and sizes), we can use the new responsive images web standard to serve appropriate image sizes for each client.

srcset syntax is necessarily verbose, so I use a Liquid include that pulls site-wide data and page data to generate a loop for each image.

Here are some snippets of code used in the demo project. To see it in even more detail, check out the demo repository on GitHub.

Site-wide variables and imgix configuration

sizes: '(min-width: 70em) 1000px, (min-width: 50em) 750px, (min-width: 31.5em) 500px, 100vw'

srcset:
  - 500
  - 750
  - 1000

## Gems configuration
gems:
  - jekyll/imgix

## Imgix configuration
imgix:
  source: demo-jekyll-imgix.imgix.net

This _config.yml file includes a string for the sizes attribute, a sequence of srcset values, and imgix configuration values.


The following examples show a sample Jekyll page or post which pull in site-wide variables to build those complex image blocks.

YAML frontmatter for the page

---
title: 'Example: `srcset` plus imgix'
image:
  - src: example-1.jpg
    alt: 'Leaves and a blue sky.'
    quality: 70
---

Liquid include on the page


{% assign image = page.image[0] %}
{% include srcset-with-imgix.html %}


Included HTML used by the page


<!-- srcset with imgix enabled -->
<!-- `image` variable assigned from front matter -->
{% if image.quality %}
  {% assign quality = image.quality %}
{% else %}
  {% assign quality = 50 %}
{% endif %}

<img
  src="{{ image.src | imgix_url: w: 500, q: 50 }}"
  sizes="{{ site.sizes }}"
  srcset="{% for width in site.srcset %}{{ image.src | imgix_url: w: width, q: quality }} {{ width }}w{% if forloop.last == false %}, {% endif %}{% endfor %}"
  alt="{{ image.alt }}">

This section uses the imgix plugin for Jekyll to process images.