Привет!

В настоящее время, интернет стал чуть ли не главной частью нашей жизни, и каждый день мы просматриваем огромное количество информации, каждый из сайтов хранит в себе множества изображений, но для того чтобы всё загружалось быстро, нам необходимо оптимизировать изображения через различные сервисы/плагины/программы и т.д. и делать это “руками” то еще занятие, поэтому всё что возможно, мы должны автоматизировать.

В данной статье мы рассмотрим как оптимизировать изображения в статическом генераторе сайтов HUGO. Рассмотрим как можно конвертировать изображения в различные форматы, изменить размер под разные экраны, настроить отложенную загрузку, как загружать их на сайте, при этом сохраняя максимальную скорость загрузки страницы.

Итак, задача у нас следующая:

  1. Создать изображения в формате webp
  2. Создать изображения под каждый экран
  3. Сделать отложенную загрузку

Итоговый результат

Вы можете посмотреть итоговый результат сразу, и после уже вернуться к дальнейшему разбору и понять всё более подробно.

Создаем новый partial:
partials/picture.html
{{ $original := .original }}
{{ with .src }}
  {{ $original = resources.GetMatch . }}
{{ end }}

{{ $convertFormats := slice "webp" }}

{{ $imageType := index (split $original.MediaType "/") 1 }}

{{ $alt := .alt }}

{{ $method := .method | default "Resize" }}

{{ $anchor := .anchor | default "Center" }}

{{ $quality := 100 }}
{{ with .quality }}{{ $quality = . }}{{ end }}
{{ $convertFormatsQuality := 85 }}{{ with .convertFormatsQuality }}{{ $convertFormatsQuality = . }}{{ end }}

{{ $columns := 12 }}
{{ $gutter := 12 }}

{{ $breakpoints := newScratch }}
{{ $breakpoints.Add "xxl" 1400 }}
{{ $breakpoints.Add "xl" 1200 }}
{{ $breakpoints.Add "lg" 992 }}
{{ $breakpoints.Add "md" 768 }}
{{ $breakpoints.Add "sm" 576 }}
{{ $breakpoints.Add "sm" 0 }}

{{ $container := newScratch }}
{{ $container.Add "xxl" 1296 }}
{{ $container.Add "xl" 1116 }}
{{ $container.Add "lg" 936 }}
{{ $container.Add "md" 696 }}
{{ $container.Add "sm" 516 }}
{{ $container.Add "xs" 516 }}

{{ $sizes := .sizes }}
{{ if eq $sizes "full" }}
  {{ $sizes = "xxl-12, xl-12, lg-12, md-12, sm-12, xs-12" }}
{{ end }}

{{ $sizeBlur := "200x" }}
{{ $blurPreview := ($original.Resize (print $sizeBlur " " $imageType " q" $quality)) }}
{{ $blurPreview := $blurPreview.Filter (images.GaussianBlur 10) }}

{{ $sizesArr := (split (replaceRE "(\\s)" "" $sizes) ",") }}
{{ $sizeValues := slice }}
{{ $sizeMax := int 0 }}
{{ $imageMax := $blurPreview }}

<figure class="{{ .classFigure }}" {{ with .cursorHoverScale }} data-cursor-hover-scale {{ end }}>
  <picture class="lazy-preload lazy-preview-show" loading="lazy">
    <span
      class="lazy-preview"
      style="background-image: url({{ $blurPreview.RelPermalink }}); background-color: transparent; background-size: cover; background-repeat: no-repeat;"
    ></span>

    {{ range $sizesArr }}
      {{ $props := (split . "-") }}

      {{ $breakpointName := index ($props) 0 }}
      {{ $breakpointSize := int ($breakpoints.Get $breakpointName) }}
      {{ $containerSize := int ($container.Get $breakpointName) }}

      {{ $imageSize := 0 }}
      {{ $image := "" }}
      {{ $isUseAnchor := false }}

      {{ if findRE "x" (index $props 1) }}
        {{ $imageSize = (index $props 1) }}
        {{ $isUseAnchor = true }}
        {{ if eq $method "Resize" }}
          {{ $method = "Fill" }}
        {{ end }}
      {{ else }}
        {{ $imageColumns := int (index $props 1) }}
        {{ $imageRatio := float (div (float $columns) (float $imageColumns)) }}
        {{ $imageSize = (print (div (float (sub $containerSize $gutter)) (float $imageRatio)) "x") }}
        {{ $isUseAnchor = false }}
      {{ end }}

      {{ $imageOptions := (print $imageSize " q" $quality " " (cond (eq $isUseAnchor true) $anchor "")) }}

      {{ if eq $method "Fill" }}
        {{ $image = ($original.Fill $imageOptions) }}
      {{ else if eq $method "Crop" }}
        {{ $image = ($original.Crop $imageOptions) }}
      {{ else if eq $method "Fit" }}
        {{ $image = ($original.Fit $imageOptions) }}
      {{ else if eq $method "Resize" }}
        {{ $image = ($original.Resize $imageOptions) }}
      {{ end }}

      {{ if gt (int $image.Width) (int $sizeMax) }}
        {{ $sizeMax = $image.Width }}
        {{ $imageMax = $image }}
      {{ end }}

      {{ if ne $imageType "gif" }}
        {{ range $convertFormats }}
          {{ $format := . }}
          {{ $imageConverted := $image }}
          {{ $imageConvertedOptions := (print $imageSize " " $format " q" $convertFormatsQuality " " (cond (eq $isUseAnchor true) $anchor "")) }}

          {{ if (eq $isUseAnchor true) }}
            {{ $imageConverted = ($original.Fill $imageConvertedOptions) }}
          {{ else }}
            {{ $imageConverted = ($original.Resize $imageConvertedOptions) }}
          {{ end }}

          <source media="(min-width: {{ $breakpointSize }}px)" data-srcset="{{ $imageConverted.RelPermalink }}" sizes="{{ $imageConverted.Width }}x{{ $imageConverted.Height }}w" width="{{ $imageConverted.Width }}" height="{{ $imageConverted.Height }}" type="{{ $imageConverted.MediaType }}" />
        {{ end }}

        <source media="(min-width: {{ $breakpointSize }}px)" data-srcset="{{ $image.RelPermalink }}" sizes="{{ $image.Width }}x{{ $image.Height }}w" width="{{ $image.Width }}" height="{{ $image.Height }}" type="{{ $image.MediaType }}" />
      {{ end }}
    {{ end }}

    <img src="{{ $blurPreview.RelPermalink }}" data-src="{{ $imageMax.RelPermalink }}" alt="{{ $alt }}" loading="lazy" width="{{ $imageMax.Width }}" height="{{ $imageMax.Height }}" type="{{ $imageMax.MediaType }}">
  </picture>
  {{ with .caption }}<figcaption>{{ . }}</figcaption>{{ end }}
</figure>
Реализация логики ленивой загрузки через js (typescript):
js/LazyLoadImage.ts
document.addEventListener('DOMContentLoaded', ev => {
  const SELECTOR = `[loading="lazy"]`
  const PRELOAD_CLASS = `.lazy-preload`

  let timeToRemove: number = 0
  const lazyImagePreviewNode = document.querySelector(`.lazy-preview`)

  if (lazyImagePreviewNode) {
    const transitionDuration = parseFloat(window.getComputedStyle(lazyImagePreviewNode).getPropertyValue(`transition-duration`)) * 1000
    const transitionDelay = parseFloat(window.getComputedStyle(lazyImagePreviewNode).getPropertyValue(`transition-delay`)) * 1000

    timeToRemove = (isNaN(transitionDuration) ? 0 : transitionDuration) + (isNaN(transitionDelay) ? 0 : transitionDelay)
  }

  const loadedHandler = (lazyContainer: HTMLElement) => {
    lazyContainer.classList.remove(PRELOAD_CLASS.slice(1))

    const previewNode = lazyContainer.querySelector(`.lazy-preview`)

    if (previewNode) {
      const removeBlurImageTimer = setTimeout(() => {

        if (previewNode) {
          previewNode.remove()
        }

        window.clearTimeout(removeBlurImageTimer)
      }, timeToRemove)
    }
  }

  const observerHandler = (entries: [IntersectionObserverEntry]) => {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if (entry.isIntersecting) {
        const lazyContainer = entry.target as HTMLElement

        // change data-src to src on container element if is equal [iframe, img, video] element
        if (lazyContainer.dataset.src) {
          const iframeElement = lazyContainer as HTMLIFrameElement

          if (iframeElement.dataset.src) {
            iframeElement.src = iframeElement.dataset.src
            delete iframeElement.dataset.src

            iframeElement.addEventListener('load', () => {
              loadedHandler(lazyContainer)
            })
          }
        }

        // change data-srcset to srcset <source>
        const sources = Array.from(lazyContainer.querySelectorAll(`[data-srcset]`)).forEach((source: HTMLSourceElement) => {
          if (source.dataset.srcset) {
            source.srcset = source.dataset.srcset
            delete source.dataset.srcset
          }
        })

        // change img data-src to src
        Array.from(lazyContainer.querySelectorAll(`[data-src]`)).forEach((element: HTMLImageElement | HTMLIFrameElement | HTMLSourceElement) => {
          if (element.dataset.src) {
            element.src = element.dataset.src
            delete element.dataset.src

            if (element.nodeName === 'IMG' || element.nodeName === 'IFRAME') {
              element.addEventListener('load', () => {
                loadedHandler(lazyContainer)
              })
            }
          }
        })

        Observer.unobserve(lazyContainer)
      }
    })
  }

  const Observer = new IntersectionObserver(observerHandler)
  const lazyContainers = Array.from(document.querySelectorAll(`${SELECTOR}`)).forEach((lazyContainer: HTMLElement) => {
    Observer.observe(lazyContainer)
  })
})

Базовая стилизация для замыленной превью через scss:

scss/lazy-image.scss
figure {
  text-align: center;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;

figcaption { width: 100%; font-size: 0.9rem; opacity: 0.5; text-decoration: none !important; } }

picture { width: 100%; position: relative; display: flex; flex-direction: row; align-items: center; justify-content: center;

.lazy-preview { z-index: 2; content: ‘’; display: block; background-color: transparent; background-size: cover; background-repeat: no-repeat; background-position: center; transition: opacity 0.6s ease-out; width: 100%; height: 100%; top: 0; left: 0; } &:not(.lazy-preload) { .lazy-preview { opacity: 0; pointer-events: none; } } &.lazy-preload { img { opacity: 0; } }

img { display: block; max-width: 100%; }

&[loading="lazy"] img { transition: opacity 0.6s ease-out; } }

Делаем preview, и подготавливаем размеры

Для начала мы создадим необходимый набор переменных:

partials/picture.html
/*
* Здесь мы извлекаем изображение и путь к нему
* В .original мы указываем путь к файлу напрямую
* В .src мы указываем путь относительно [rootDir]/assets/ 
* */
{{ $original := .original }}
{{ with .src }}
  {{ $original = resources.GetMatch . }}
{{ end }}
 
/*
* Указываем в какие форматы на нужно конвертировать исходное изображение
* Добавлять можно через пробел
* Пример: $convertFormats := slice "webp" "tif"
* */
{{ $convertFormats := slice "webp" }}

/*
* Получаем расширение исходного изображения
* $original = your_image.png
* Получим $imageType = "png"
* */
{{ $imageType := index (split $original.MediaType "/") 1 }}

/*
* Получаем текст для аттрибута alt
* К .alt можно добавить значение по умолчанию:
* {{ $alt := .alt | default "Picture" }}
* */
{{ $alt := .alt }}

/*
* Метод изменения размера
* Resize - Изменить размер
* Crop - Обрезать
* Fit - Вписать
* Fill - Заполнить
* */
{{ $method := .method | default "Resize" }}

/*
* Точка привязки (Anchor point) указывается только в случаях когда method = Crop || Fill
* Варианты Anchor point - TopLeft, Top, TopRight, Left, Center,Right, BottomLeft, Bottom, BottomRight, Smart
* */
{{ $anchor := .anchor | default "Center" }}

/*
* Указываем качество для исходного файла - $quality, и для изображений других форматов - $convertFormatQuality
* */
{{ $quality := 100 }}
{{ with .quality }}{{ $quality = . }}{{ end }}
{{ $convertFormatsQuality := 85 }}{{ with .convertFormatsQuality }}{{ $convertFormatsQuality = . }}{{ end }}

/*
* Размеры для сетки Bootstrap
* $columns - количество колонок
* $gutter - расстояние между колонками (необходимо для того чтобы вписаться в колонки)
* */
{{ $columns := 12 }}
{{ $gutter := 12 }}

/*
* Breakpoints для контейнера
* */
{{ $breakpoints := newScratch }}
{{ $breakpoints.Add "xxl" 1400 }}
{{ $breakpoints.Add "xl" 1200 }}
{{ $breakpoints.Add "lg" 992 }}
{{ $breakpoints.Add "md" 768 }}
{{ $breakpoints.Add "sm" 576 }}
{{ $breakpoints.Add "sm" 0 }}

/*
* Размеры контейнера при различных breakpoint
* */
{{ $container := newScratch }}
{{ $container.Add "xxl" 1296 }}
{{ $container.Add "xl" 1116 }}
{{ $container.Add "lg" 936 }}
{{ $container.Add "md" 696 }}
{{ $container.Add "sm" 516 }}
{{ $container.Add "xs" 516 }}

/*
* Размер изображения, указывать можно как точный размер, так и количество занимаемых колонок
* Например: size "xxl-12, xl-10, md-8, xs-12"
* Например: size "xxl-12, xl-12, md-640x480, xs-320x"
* */
{{ $sizes := .sizes }}
{{ if eq $sizes "full" }}
  {{ $sizes = "xxl-12, xl-12, lg-12, md-12, sm-12, xs-12" }}
{{ end }}

/*
* Создание preview, указываем размеры, и коэфициент размытия изображения
* */
{{ $sizeBlur := "200x" }}
{{ $blurPreview := ($original.Resize (print $sizeBlur " " $imageType " q" $quality)) }}
{{ $blurPreview := $blurPreview.Filter (images.GaussianBlur 10) }}

/*
* Приватные переменные
* В переменной $sizeArr мы храним массив с размерами
* */
{{ $sizesArr := (split (replaceRE "(\\s)" "" $sizes) ",") }}
{{ $sizeValues := slice }}
{{ $sizeMax := int 0 }}
{{ $imageMax := $blurPreview }}

Конвертируем, изменяем размер и ставим preview для изображения

partials/picture.html
/*
* Создаем тэг figure (> picture > span > img) + caption
* */
<figure class="{{ .classFigure }}">
  <picture class="lazy-preload" loading="lazy">
    <span
      class="lazy-preview"
      style="background-image: url({{ $blurPreview.RelPermalink }}); background-color: transparent; background-size: cover; background-repeat: no-repeat;"
    ></span>

    /*
    * Проходимся по всем указанным размерам
    * */
    {{ range $sizesArr }}
      /*
      * В переменной $props мы получаем размер и breakpoint
      * $props := slice "xxl" "12"
      * */
      {{ $props := (split . "-") }}

      // $breakpointName := "xxl"
      {{ $breakpointName := index ($props) 0 }}
      // $breakpointSize := 1400 [$breakpoints["xxl"] = 1400]
      {{ $breakpointSize := int ($breakpoints.Get $breakpointName) }}
      // $breakpointName := 1296 [$container["xxl"] = 1296]
      {{ $containerSize := int ($container.Get $breakpointName) }}
  
      /*
      * Создаем необходимые переменные
      * $imageSize := размер изображения
      * $image := экземляр изображения (с уже измененным размером)
      * $isUseAnchor := использовать ли anchor point (например когда указано в точных значениях)
      * */
      {{ $imageSize := 0 }}
      {{ $imageWebp := "" }}
      {{ $image := "" }}
      {{ $isUseAnchor := false }}

      /*
      * Получаем размер изображения
      * Если мы находим "x", значит размер у нас указан в точных числах,
      * отсюда мы автоматически подключаем использование anchor point
      * Если у нас указано количество колонок (т.е. число),
      * то высчитываем размер относительно текущего контейнера в текущем breakpoint
      * !!! ВАЖНО, лучше всего использовать hugo-extended чтобы всё работало нормально
      * */
      {{ if findRE "x" (index $props 1) }}
        {{ $imageSize = (index $props 1) }}
        {{ $isUseAnchor = true }}
        {{ if eq $method "Resize" }}
          {{ $method = "Fill" }}
        {{ end }}
      {{ else }}
        {{ $imageColumns := int (index $props 1) }}
        {{ $imageRatio := float (div (float $columns) (float $imageColumns)) }}
        {{ $imageSize = (print (div (float (sub $containerSize $gutter)) (float $imageRatio)) "x") }}
        {{ $isUseAnchor = false }}
      {{ end }}

      /*
      * Устанавливаем опции конвертации и изменения размера изображения
      * */
      {{ $imageOptions := (print $imageSize " q" $quality " " (cond (eq $isUseAnchor true) $anchor "")) }}

      /*
      * Создаем новое изображение с новым размером
      * */
      {{ if eq $method "Fill" }}
        {{ $image = ($original.Fill $imageOptions) }}
      {{ else if eq $method "Crop" }}
        {{ $image = ($original.Crop $imageOptions) }}
      {{ else if eq $method "Fit" }}
        {{ $image = ($original.Fit $imageOptions) }}
      {{ else if eq $method "Resize" }}
        {{ $image = ($original.Resize $imageOptions) }}
      {{ end }}

      /*
      * Находим самое большое изображение для того,
      * чтобы вставить его в тэг img по умолчанию
      * может быть так что оригинал в размере 3840x2160 px
      * но самое большое изображение которое есть на странице имеет размер 1296x729 px
      * также с максимально большого изображения мы берем размер width и height
      * */
      {{ if gt (int $image.Width) (int $sizeMax) }}
        {{ $sizeMax = $image.Width }}
        {{ $imageMax = $image }}
      {{ end }}

      /*
      * Создаем изображения в указаных нами форматах
      * Если формат изображения "gif", то мы не создаем другие форматы
      * gif изображения просто добавляются в data-src и потом подменяются в src
      * gif не поджимаются, т.к. при изменении размера gif, анимация не работает
      * */
      {{ if ne $imageType "gif" }}
        {{ range $convertFormats }}
          {{ $format := . }}
          {{ $imageConverted := $image }}
          {{ $imageConvertedOptions := (print $imageSize " " $format " q" $convertFormatsQuality " " (cond (eq $isUseAnchor true) $anchor "")) }}

          {{ if (eq $isUseAnchor true) }}
            {{ $imageConverted = ($original.Fill $imageConvertedOptions) }}
          {{ else }}
            {{ $imageConverted = ($original.Resize $imageConvertedOptions) }}
          {{ end }}
    
          /*
          * Подключаем изображение в других форматах (webp)
          * а также в разных размерах (медиа запросы)
          * */
          <source media="(min-width: {{ $breakpointSize }}px)" data-srcset="{{ $imageConverted.RelPermalink }}" sizes="{{ $imageConverted.Width }}x{{ $imageConverted.Height }}w" width="{{ $imageConverted.Width }}" height="{{ $imageConverted.Height }}" type="{{ $imageConverted.MediaType }}" />
        {{ end }}
    
        /*
        * Подключаем изображение в разных размерах (медиа запросы)
        * */
        <source media="(min-width: {{ $breakpointSize }}px)" data-srcset="{{ $image.RelPermalink }}" sizes="{{ $image.Width }}x{{ $image.Height }}w" width="{{ $image.Width }}" height="{{ $image.Height }}" type="{{ $image.MediaType }}" />
      {{ end }}
    {{ end }}

    /*
    * Устанавливаем в src изображения с размытием, сначала будет грузиться оно, но оно очень мало весит
    * В data-src ставим уже изображение с максимальным размером которое мы высчитывали ранее
    * С изображения с максимальным размером мы берем width и height для того, чтобы бразер подготовил место под это изображения
    * */
    <img src="{{ $blurPreview.RelPermalink }}" data-src="{{ $imageMax.RelPermalink }}" alt="{{ $alt }}" loading="lazy" width="{{ $imageMax.Width }}" height="{{ $imageMax.Height }}" type="{{ $imageMax.MediaType }}">
  </picture>

  /*
  * Устанавливаем caption
  * */
  {{ with .caption }}<figcaption>{{ . }}</figcaption>{{ end }}
</figure>

Создаем отложенную загрузку

js/LazyLoadImage.ts
document.addEventListener('DOMContentLoaded', ev => {
  const SELECTOR = `[loading="lazy"]`
  const PRELOAD_CLASS = `.lazy-preload`

  let timeToRemove: number = 0
  const lazyImagePreviewNode = document.querySelector(`.lazy-preview`)

  if (lazyImagePreviewNode) {
    const transitionDuration = parseFloat(window.getComputedStyle(lazyImagePreviewNode).getPropertyValue(`transition-duration`)) * 1000
    const transitionDelay = parseFloat(window.getComputedStyle(lazyImagePreviewNode).getPropertyValue(`transition-delay`)) * 1000

    timeToRemove = (isNaN(transitionDuration) ? 0 : transitionDuration) + (isNaN(transitionDelay) ? 0 : transitionDelay)
  }

  const loadedHandler = (lazyContainer: HTMLElement) => {
    lazyContainer.classList.remove(PRELOAD_CLASS.slice(1))

    const previewNode = lazyContainer.querySelector(`.lazy-preview`)

    if (previewNode) {
      const removeBlurImageTimer = setTimeout(() => {

        if (previewNode) {
          previewNode.remove()
        }

        window.clearTimeout(removeBlurImageTimer)
      }, timeToRemove)
    }
  }

  const observerHandler = (entries: [IntersectionObserverEntry]) => {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if (entry.isIntersecting) {
        const lazyContainer = entry.target as HTMLElement

        // change data-src to src on container element if is equal [iframe, img, video] element
        if (lazyContainer.dataset.src) {
          const iframeElement = lazyContainer as HTMLIFrameElement

          if (iframeElement.dataset.src) {
            iframeElement.src = iframeElement.dataset.src
            delete iframeElement.dataset.src

            iframeElement.addEventListener('load', () => {
              loadedHandler(lazyContainer)
            })
          }
        }

        // change data-srcset to srcset <source>
        const sources = Array.from(lazyContainer.querySelectorAll(`[data-srcset]`)).forEach((source: HTMLSourceElement) => {
          if (source.dataset.srcset) {
            source.srcset = source.dataset.srcset
            delete source.dataset.srcset
          }
        })

        // change img data-src to src
        Array.from(lazyContainer.querySelectorAll(`[data-src]`)).forEach((element: HTMLImageElement | HTMLIFrameElement | HTMLSourceElement) => {
          if (element.dataset.src) {
            element.src = element.dataset.src
            delete element.dataset.src

            if (element.nodeName === 'IMG' || element.nodeName === 'IFRAME') {
              element.addEventListener('load', () => {
                loadedHandler(lazyContainer)
              })
            }
          }
        })

        Observer.unobserve(lazyContainer)
      }
    })
  }

  const Observer = new IntersectionObserver(observerHandler)
  const lazyContainers = Array.from(document.querySelectorAll(`${SELECTOR}`)).forEach((lazyContainer: HTMLElement) => {
    Observer.observe(lazyContainer)
  })
})

Также настроим стили

scss/lazy-image.scss
figure {
  text-align: center;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;

  figcaption {
    width: 100%;
    font-size: 0.9rem;
    opacity: 0.5;
    text-decoration: none !important;
  }
}

picture {
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;

  .lazy-preview {
    z-index: 2;
    content: '';
    display: block;
    background-color: transparent;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    transition: opacity 0.6s ease-out;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
  &:not(.lazy-preload) {
    .lazy-preview {
      opacity: 0;
      pointer-events: none;
    }
  }
  &.lazy-preload {
    img {
      opacity: 0;
    }
  }

  img {
    display: block;
    max-width: 100%;
  }

  &[loading="lazy"] img {
    transition: opacity 0.6s ease-out;
  }
}

Как вызывать partial

layouts/index.html
{{ partial "picture" (dict
  "src" "/media/featured-image.jpg"
  "sizes" "xxl-10, xl-2, lg-12, sm-12, xs-360x240"
  "alt" "Featured image"
) }}

Демо