DEV Community

Cover image for Gatsby Images and Safari
Nate Arnold
Nate Arnold

Posted on

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.

Top comments (4)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
arnonate profile image
Nate Arnold • Edited

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
 
gizmofalcon profile image
Sourabh Daroji

This solution is valid for gatsby-plugin-image as well!

Collapse
 
l00sed profile image
Daniel Tompkins

This is really interesting and important! Thanks for sharing.