loading...
Cover image for Gatsby Images and Safari

Gatsby Images and Safari

arnonate profile image Nate Arnold ・1 min read

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.

Discussion

pic
Editor guide
Collapse
johnridesabike profile image
John Jackson

I thought only IE doesn’t support intersection observer? I’ve been using gatsby-image with no extra polyfill and my images have always loaded fine on Safari. I believe Gatsby automatically includes a polyfill for IE.

Collapse
arnonate profile image
Nate Arnold Author

Weird. You are right that Gatsby Image ships with a polyfill for IE import Img from "gatsby-image/withIEPolyfill, but this is only a polyfill for the object-fit CSS prop I believe. This blog post is the only way I could get my images to show up in Safari. To be clear, these are the settings I am using: ...GatsbyImageSharpFluid_withWebp_noBase64.

Collapse
johnridesabike profile image
John Jackson

That’s odd. It may be worth filing an issue on the Gatsby repo. I’ve never had a problem with it and Safari.

Collapse
l00sed profile image
Daniel Tompkins

This is really interesting and important! Thanks for sharing.