{"id":27734243,"url":"https://github.com/pixel-point/gatsby-image-lazy-offset","last_synced_at":"2025-04-28T13:05:09.886Z","repository":{"id":100606792,"uuid":"209518523","full_name":"pixel-point/gatsby-image-lazy-offset","owner":"pixel-point","description":null,"archived":false,"fork":false,"pushed_at":"2019-09-19T09:49:45.000Z","size":20,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-28T13:03:05.452Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pixel-point.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-09-19T09:49:29.000Z","updated_at":"2019-09-19T09:49:47.000Z","dependencies_parsed_at":"2023-05-16T07:30:42.970Z","dependency_job_id":null,"html_url":"https://github.com/pixel-point/gatsby-image-lazy-offset","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pixel-point%2Fgatsby-image-lazy-offset","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pixel-point%2Fgatsby-image-lazy-offset/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pixel-point%2Fgatsby-image-lazy-offset/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pixel-point%2Fgatsby-image-lazy-offset/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pixel-point","download_url":"https://codeload.github.com/pixel-point/gatsby-image-lazy-offset/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251319599,"owners_count":21570426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-28T13:02:51.491Z","updated_at":"2025-04-28T13:05:09.862Z","avatar_url":"https://github.com/pixel-point.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gatsby-image\n\nSpeedy, optimized images without the work.\n\n`gatsby-image` is a React component specially designed to work seamlessly with\nGatsby's GraphQL queries. It combines\n[Gatsby's native image processing](https://image-processing.gatsbyjs.org/)\ncapabilities with advanced image loading techniques to easily and completely\noptimize image loading for your sites. `gatsby-image` uses\n[gatsby-plugin-sharp](/packages/gatsby-plugin-sharp/)\nto power its image transformations.\n\n_Note: gatsby-image is **not** a drop-in replacement for `\u003cimg /\u003e`. It's\noptimized for fixed width/height images and images that stretch the full-width\nof a container. Some ways you can use `\u003cimg /\u003e` won't work with gatsby-image._\n\n**[Demo](https://using-gatsby-image.gatsbyjs.org)**\n\n## Table of Contents\n\n- [Problem](#problem)\n- [Solution](#solution)\n- [Install](#install)\n- [How to use](#how-to-use)\n- [Polyfilling object-fit/object-position for IE](#polyfilling-object-fitobject-position-for-ie)\n- [Types of Responsive Images](#two-types-of-responsive-images)\n- [Fragments](#fragments)\n  - [gatsby-transformer-sharp](#gatsby-transformer-sharp)\n  - [gatsby-source-contentful](#gatsby-source-contentful)\n  - [gatsby-source-datocms](#gatsby-source-datocms)\n  - [gatsby-source-sanity](#gatsby-source-sanity)\n- [Fixed Queries](#fixed-queries)\n- [Fluid Queries](#fluid-queries)\n- [Art directing multiple images](#art-directing-multiple-images)\n- [Gatsby Image Props](#gatsby-image-props)\n- [Image Processing Arguments](#image-processing-arguments)\n- [Other Stuff](#some-other-stuff-to-be-aware-of)\n\n## Problem\n\nLarge, unoptimized images dramatically slow down your site.\n\nBut creating optimized images for websites has long been a thorny problem.\nIdeally you would:\n\n- Resize large images to the size needed by your design\n- Generate multiple smaller images so smartphones and tablets don't download\n  desktop-sized images\n- Strip all unnecessary metadata and optimize JPEG and PNG compression\n- Efficiently lazy load images to speed initial page load and save bandwidth\n- Use the \"blur-up\" technique or a\n  \"[traced placeholder](https://github.com/gatsbyjs/gatsby/issues/2435)\" SVG to\n  show a preview of the image while it loads\n- Hold the image position so your page doesn't jump while images load\n\nDoing this consistently across a site feels like sisyphean labor. You manually\noptimize your images and then… several images are swapped in at the last minute\nor a design-tweak shaves 100px of width off your images.\n\nMost solutions involve a lot of manual labor and bookkeeping to ensure every\nimage is optimized.\n\nThis isn't ideal. Optimized images should be easy and the default.\n\n## Solution\n\nWith Gatsby, we can make images way _way_ better.\n\n`gatsby-image` is designed to work seamlessly with Gatsby's native image\nprocessing capabilities powered by GraphQL and Sharp. To produce perfect images,\nyou need only:\n\n1. Import `gatsby-image` and use it in place of the built-in `img`\n2. Write a GraphQL query using one of the included GraphQL \"fragments\"\n   which specify the fields needed by `gatsby-image`.\n\nThe GraphQL query creates multiple thumbnails with optimized JPEG and PNG\ncompression. The `gatsby-image` component automatically sets up the \"blur-up\"\neffect as well as lazy loading of images further down the screen.\n\n## Install\n\n`npm install --save gatsby-image`\n\nDepending on the gatsby starter you used, you may need to include [gatsby-transformer-sharp](/packages/gatsby-transformer-sharp/) and [gatsby-plugin-sharp](/packages/gatsby-plugin-sharp/) as well, and make sure they are installed and included in your gatsby-config.\n\n```bash\nnpm install --save gatsby-transformer-sharp gatsby-plugin-sharp\n```\n\nThen in your `gatsby-config.js`:\n\n```js\nplugins: [`gatsby-transformer-sharp`, `gatsby-plugin-sharp`]\n```\n\nAlso, make sure you have set up a source plugin, so your images are available in `graphql` queries. For example, if your images live in a project folder on the local filesystem, you would set up `gatsby-source-filesystem` in `gatsby-config.js` like so:\n\n```js\nconst path = require(`path`)\n\nmodule.exports = {\n  plugins: [\n    {\n      resolve: `gatsby-source-filesystem`,\n      options: {\n        name: `images`,\n        path: path.join(__dirname, `src`, `images`),\n      },\n    },\n    `gatsby-plugin-sharp`,\n    `gatsby-transformer-sharp`,\n  ],\n}\n```\n\n## How to use\n\nThis is what a component using `gatsby-image` looks like:\n\n```jsx\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\nimport Img from \"gatsby-image\"\n\nexport default ({ data }) =\u003e (\n  \u003cdiv\u003e\n    \u003ch1\u003eHello gatsby-image\u003c/h1\u003e\n    \u003cImg fixed={data.file.childImageSharp.fixed} /\u003e\n  \u003c/div\u003e\n)\n\nexport const query = graphql`\n  query {\n    file(relativePath: { eq: \"blog/avatars/kyle-mathews.jpeg\" }) {\n      childImageSharp {\n        # Specify the image processing specifications right in the query.\n        # Makes it trivial to update as your page's design changes.\n        fixed(width: 125, height: 125) {\n          ...GatsbyImageSharpFixed\n        }\n      }\n    }\n  }\n`\n```\n\nFor other explanations of how to get started with gatsby-image, see this blog post by community member Kyle Gill [Image Optimization Made Easy with Gatsby.js](https://medium.com/@kyle.robert.gill/ridiculously-easy-image-optimization-with-gatsby-js-59d48e15db6e) or this one by Hunter Chang (which also includes some details about changes to gatsby-image for Gatsby v2): [An Intro To Gatsby Image V2](https://codebushi.com/using-gatsby-image/)\n\n## Polyfilling object-fit/object-position for IE\n\nIf you'd like to include a polyfill for the [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)/[`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS properties (which [aren't supported](https://caniuse.com/#feat=object-fit) by default in Internet Explorer), import from `gatsby-image/withIEPolyfill` instead:\n\n```jsx\n// Other imports...\nimport Img from \"gatsby-image/withIEPolyfill\"\n\nexport default ({ data }) =\u003e (\n  \u003cdiv\u003e\n    \u003ch1\u003eHello gatsby-image\u003c/h1\u003e\n    \u003cImg\n      fixed={data.file.childImageSharp.fixed}\n      objectFit=\"cover\"\n      objectPosition=\"50% 50%\"\n      alt=\"\"\n    /\u003e\n  \u003c/div\u003e\n)\n\n// GraphQL query...\n```\n\nImporting from `gatsby-image/withIEPolyfill` tells Gatsby to automatically apply the `object-fit-images` polyfill to your image. To make your `object-fit`/`object-position` values work in IE, be sure to use the `objectFit` and `objectPosition` props (rather than the `imgStyle` prop or a CSS or CSS-in-JS solution) so the polyfill will recognize them.\n\n## Two types of responsive images\n\nThere are two types of responsive images supported by gatsby-image.\n\n1. Images that have a _fixed_ width and height\n2. Images that stretch across a _fluid_ container\n\nIn the first scenario, you want to vary the image's size for different screen\nresolutions -- in other words, create retina images.\n\nFor the second scenario, you want to create multiple sizes of thumbnails for\ndevices with widths stretching from smartphone to wide desktop monitors.\n\nTo decide between the two, ask yourself: \"do I know the exact size this image\nwill be?\" If yes, it's the first type. If no and its width and/or height need to\nvary depending on the size of the screen, then it's the second type.\n\nIn Gatsby's GraphQL implementation, you query for the first type by querying a\nchild object of an image called `fixed` — which you can see in the sample\ncomponent above. For the second type, you do a similar query but for a child\nobject called `fluid`.\n\n## Fragments\n\nGraphQL includes a concept called \"query fragments\". Which, as the name\nsuggests, are a part of a query that can be used in multiple queries. To ease\nbuilding with `gatsby-image`, Gatsby image processing plugins which support\n`gatsby-image` ship with fragments which you can easily include in your queries.\n\nNote,\n[due to a limitation of GraphiQL](https://github.com/graphql/graphiql/issues/612),\nyou can not currently use these fragments in the GraphiQL IDE.\n\nPlugins supporting `gatsby-image` currently include\n[gatsby-transformer-sharp](/packages/gatsby-transformer-sharp/),\n[gatsby-source-contentful](/packages/gatsby-source-contentful/), [gatsby-source-datocms](https://github.com/datocms/gatsby-source-datocms) and [gatsby-source-sanity](https://github.com/sanity-io/gatsby-source-sanity).\n\nTheir fragments are:\n\n### gatsby-transformer-sharp\n\n- `GatsbyImageSharpFixed`\n- `GatsbyImageSharpFixed_noBase64`\n- `GatsbyImageSharpFixed_tracedSVG`\n- `GatsbyImageSharpFixed_withWebp`\n- `GatsbyImageSharpFixed_withWebp_noBase64`\n- `GatsbyImageSharpFixed_withWebp_tracedSVG`\n- `GatsbyImageSharpFluid`\n- `GatsbyImageSharpFluid_noBase64`\n- `GatsbyImageSharpFluid_tracedSVG`\n- `GatsbyImageSharpFluid_withWebp`\n- `GatsbyImageSharpFluid_withWebp_noBase64`\n- `GatsbyImageSharpFluid_withWebp_tracedSVG`\n\n### gatsby-source-contentful\n\n- `GatsbyContentfulFixed`\n- `GatsbyContentfulFixed_noBase64`\n- `GatsbyContentfulFixed_tracedSVG`\n- `GatsbyContentfulFixed_withWebp`\n- `GatsbyContentfulFixed_withWebp_noBase64`\n- `GatsbyContentfulFluid`\n- `GatsbyContentfulFluid_noBase64`\n- `GatsbyContentfulFluid_tracedSVG`\n- `GatsbyContentfulFluid_withWebp`\n- `GatsbyContentfulFluid_withWebp_noBase64`\n\n### gatsby-source-datocms\n\n- `GatsbyDatoCmsFixed`\n- `GatsbyDatoCmsFixed_noBase64`\n- `GatsbyDatoCmsFluid`\n- `GatsbyDatoCmsFluid_noBase64`\n\n### gatsby-source-sanity\n\n- `GatsbySanityImageFixed`\n- `GatsbySanityImageFixed_noBase64`\n- `GatsbySanityImageFluid`\n- `GatsbySanityImageFluid_noBase64`\n\nIf you don't want to use the blur-up effect, choose the fragment with `noBase64`\nat the end. If you want to use the traced placeholder SVGs, choose the fragment\nwith `tracedSVG` at the end.\n\nIf you want to automatically use WebP images when the browser supports the file\nformat, use the `withWebp` fragments. If the browser doesn't support WebP,\n`gatsby-image` will fall back to the default image format.\n\n_Please see the\n[gatsby-plugin-sharp](/packages/gatsby-plugin-sharp/#tracedsvg)\ndocumentation for more information on `tracedSVG` and its configuration\noptions._\n\n## \"Fixed\" queries\n\n### Component\n\nPass in the data returned from the `fixed` object in your query via the\n`fixed` prop. e.g. `\u003cImg fixed={fixed} /\u003e`\n\n### Query\n\n```graphql\n{\n  imageSharp {\n    # Other options include height (set both width and height to crop),\n    # grayscale, duotone, rotate, etc.\n    fixed(width: 400) {\n      # Choose either the fragment including a small base64ed image, a traced placeholder SVG, or one without.\n      ...GatsbyImageSharpFixed\n    }\n  }\n}\n```\n\n## \"Fluid\" queries\n\n### Component\n\nPass in the data returned from the `fluid` object in your query via the `fluid`\nprop. e.g. `\u003cImg fluid={fluid} /\u003e`\n\n### Query\n\n```graphql\n{\n  imageSharp {\n    # i.e. the max width of your container is 700 pixels.\n    #\n    # Other options include maxHeight (set both maxWidth and maxHeight to crop),\n    # grayscale, duotone, rotate, etc.\n    fluid(maxWidth: 700) {\n      # Choose either the fragment including a small base64ed image, a traced placeholder SVG, or one without.\n      ...GatsbyImageSharpFluid_noBase64\n    }\n  }\n}\n```\n\n### Avoiding stretched images using the fluid type\n\nAs mentioned previously, images using the _fluid_ type are stretched to\nmatch the container's width. In the case where the image's width is smaller than the available viewport, the image will stretch to match the container, potentially leading to unwanted problems and worsened image quality.\n\nTo counter this edge case one could wrap the _Img_ component in order to set a better, for that case, `maxWidth`:\n\n```jsx\nconst NonStretchedImage = props =\u003e {\n  let normalizedProps = props\n  if (props.fluid \u0026\u0026 props.fluid.presentationWidth) {\n    normalizedProps = {\n      ...props,\n      style: {\n        ...(props.style || {}),\n        maxWidth: props.fluid.presentationWidth,\n        margin: \"0 auto\", // Used to center the image\n      },\n    }\n  }\n\n  return \u003cImg {...normalizedProps} /\u003e\n}\n```\n\n**Note:** The `GatsbyImageSharpFluid` fragment does not include `presentationWidth`.\nYou will need to add it in your graphql query as is shown in the following snippet:\n\n```graphql\n{\n  childImageSharp {\n    fluid(maxWidth: 500, quality: 100) {\n      ...GatsbyImageSharpFluid\n      presentationWidth\n    }\n  }\n}\n```\n\n## Art-directing multiple images\n\n`gatsby-image` supports showing different images at different breakpoints, which is known as [art direction](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#Art_direction). To do this, you can define your own array of `fixed` or `fluid` images, along with a `media` key per image, and pass it to `gatsby-image`'s `fixed` or `fluid` props. The `media` key that is set on an image can be any valid CSS media query.\n\n```jsx\nimport React from \"react\"\nimport { graphql } from \"gatsby\"\nimport Img from \"gatsby-image\"\n\nexport default ({ data }) =\u003e {\n  // Set up the array of image data and `media` keys.\n  // You can have as many entries as you'd like.\n  const sources = [\n    data.mobileImage.childImageSharp.fluid,\n    {\n      ...data.desktopImage.childImageSharp.fluid,\n      media: `(min-width: 768px)`,\n    },\n  ]\n\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003eHello art-directed gatsby-image\u003c/h1\u003e\n      \u003cImg fluid={sources} /\u003e\n    \u003c/div\u003e\n  )\n}\n\nexport const query = graphql`\n  query {\n    mobileImage: file(relativePath: { eq: \"blog/avatars/kyle-mathews.jpeg\" }) {\n      childImageSharp {\n        fluid(maxWidth: 1000, quality: 100) {\n          ...GatsbyImageSharpFluid\n        }\n      }\n    }\n    desktopImage: file(\n      relativePath: { eq: \"blog/avatars/kyle-mathews-desktop.jpeg\" }\n    ) {\n      childImageSharp {\n        fluid(maxWidth: 2000, quality: 100) {\n          ...GatsbyImageSharpFluid\n        }\n      }\n    }\n  }\n`\n```\n\nWhile you could achieve a similar effect with plain CSS media queries, `gatsby-image` accomplishes this using the `\u003cpicture\u003e` tag, which ensures that browsers only download the image they need for a given breakpoint.\n\n## `gatsby-image` props\n\n| Name                   | Type                | Description                                                                                                                                   |\n| ---------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `fixed`                | `object` / `array`  | Data returned from the `fixed` query. When prop is an array it has to be combined with `media` keys, allows for art directing `fixed` images. |\n| `fluid`                | `object` / `array`  | Data returned from the `fluid` query. When prop is an array it has to be combined with `media` keys, allows for art directing `fluid` images. |\n| `fadeIn`               | `bool`              | Defaults to fading in the image on load                                                                                                       |\n| `durationFadeIn`       | `number`            | fading duration is set up to 500ms by default                                                                                                 |\n| `title`                | `string`            | Passed to the `img` element                                                                                                                   |\n| `alt`                  | `string`            | Passed to the `img` element. Defaults to an empty string `alt=\"\"`                                                                             |\n| `crossOrigin`          | `string`            | Passed to the `img` element                                                                                                                   |\n| `className`            | `string` / `object` | Passed to the wrapper element. Object is needed to support Glamor's css prop                                                                  |\n| `style`                | `object`            | Spread into the default styles of the wrapper element                                                                                         |\n| `imgStyle`             | `object`            | Spread into the default styles of the actual `img` element                                                                                    |\n| `placeholderStyle`     | `object`            | Spread into the default styles of the placeholder `img` element                                                                               |\n| `placeholderClassName` | `string`            | A class that is passed to the placeholder `img` element                                                                                       |\n| `backgroundColor`      | `string` / `bool`   | Set a colored background placeholder. If true, uses \"lightgray\" for the color. You can also pass in any valid color string.                   |\n| `onLoad`               | `func`              | A callback that is called when the full-size image has loaded.                                                                                |\n| `onStartLoad`          | `func`              | A callback that is called when the full-size image starts loading, it gets the parameter { wasCached: boolean } provided.                     |\n| `onError`              | `func`              | A callback that is called when the image fails to load.                                                                                       |\n| `Tag`                  | `string`            | Which HTML tag to use for wrapping elements. Defaults to `div`.                                                                               |\n| `objectFit`            | `string`            | Passed to the `object-fit-images` polyfill when importing from `gatsby-image/withIEPolyfill`. Defaults to `cover`.                            |\n| `objectPosition`       | `string`            | Passed to the `object-fit-images` polyfill when importing from `gatsby-image/withIEPolyfill`. Defaults to `50% 50%`.                          |\n| `loading`              | `string`            | Set the browser's native lazy loading attribute. One of `lazy`, `eager` or `auto`. Defaults to `lazy`.                                        |\n| `critical`             | `bool`              | Opt-out of lazy-loading behavior. Defaults to `false`. Deprecated, use `loading` instead.                                                     |\n| `fixedImages`          | `array`             | An array of objects returned from `fixed` queries. When combined with `media` keys, allows for art directing `fixed` images.                  |\n| `fluidImages`          | `array`             | An array of objects returned from `fluid` queries. When combined with `media` keys, allows for art directing `fluid` images.                  |\n| `draggable`            | `bool`              | Set the img tag draggable to either `false`, `true`                                                                                           |\n| `itemProp`             | `string`            | Add an [`itemprop` schema.org structured data attribute](https://schema.org/docs/gs.html#microdata_itemprop) on the image.                    |\n| `lazyOffset`           | `string`            | An offset for lazy-loading. The same as `IntersectionObserver.rootMargin`, Defaults to `200px`.                                               |\n\n## Image processing arguments\n\n[gatsby-plugin-sharp](/packages/gatsby-plugin-sharp) supports many additional arguments for transforming your images like\n`quality`, `sizeByPixelDensity`, `pngCompressionLevel`, `cropFocus`, `grayscale` and many more. See its documentation for more.\n\n## Some other stuff to be aware of\n\n- If you want to set `display: none;` on a component using a `fixed` prop,\n  you need to also pass in to the style prop `{ display: 'inherit' }`.\n- Be aware that from a SEO perspective it is advisable not to change the image parameters lightheartedly once the website has been published. Every time you change properties within _fluid_ or _fixed_ (like _quality_ or _maxWidth_), the absolute path of the image changes. These properties generate the hash we use in our absolute path. This happens even if the image didn't change its name. As a result, the image could appear on the image SERP as \"new\" one. (more details [can be found on this issue](https://github.com/gatsbyjs/gatsby/issues/13742))\n- By default, images don't load until JavaScript is loaded. Gatsby's automatic code\n  splitting generally makes this fine but if images seem slow coming in on a\n  page, check how much JavaScript is being loaded there.\n- Images marked as `critical` will start loading immediately as the DOM is\n  parsed, but unless `fadeIn` is set to `false`, the transition from placeholder\n  to final image will not occur until after the component is mounted.\n- gatsby-image is now backed by the newer `\u003cpicture\u003e` tag. This newer standard allows for\n  media types to be chosen by the browser without using JavaScript. It also is\n  backward compatible to older browsers (IE 11, etc)\n- Gifs can't be resized the same way as pngs and jpegs, unfortunately—if you try\n  to use a gif with `gatsby-image`, it won't work. For now, the best workaround is\n  to [import the gif directly](/docs/adding-images-fonts-files).\n- Lazy loading behavior is dependent on `IntersectionObserver` which is not available\n  in IE. A polyfill is recommended.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpixel-point%2Fgatsby-image-lazy-offset","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpixel-point%2Fgatsby-image-lazy-offset","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpixel-point%2Fgatsby-image-lazy-offset/lists"}