Gatsby Images and Safari

arnonate

Nate Arnold

Posted on September 4, 2020

Gatsby Images and Safari

By default Gatsby image places a loading: "lazy" attribute on all images created by the gatbsy-image package. This attribute causes images on the page wait to load until they are in view. When used in conjunction with Low Quality Image Placeholders, the result is a really nice experience in most modern browsers that is performant and aesthetically pleasing.

Safari, however, is yet to implement an important browser API that gatsby-image depends on... Intersection Observer. This can lead to images never loading or loading in an lqip state and never updating.

According to the MDN docs:

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

This feature is necessary in order to update the image's source once it is in view, which never happens in Safari desktop or iOS.

Luckily, the fix is easy. Simply install the polyfill:

yarn add intersection-observer

Next, let Gatbsy know that you want to load the polyfill once the browser APIs are available. Open up gatsby-browser.js and copy the following snippet:

/**
 * Implement Gatsby's Browser APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/browser-apis/
 */

export const onClientEntry = async () => {
  if (typeof IntersectionObserver === "undefined") {
    await import("intersection-observer")
  }
}

Viola! Performant images in Safari with gatsby-image!

You can check out my Gatbsy/WordPress Starter repo for an example of this polyfill in action.

💖 💪 🙅 🚩
arnonate
Nate Arnold

Posted on September 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Gatsby Images and Safari
gatsby Gatsby Images and Safari

September 4, 2020