Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Extract the Height of a Lazy Loaded Image Using Gridsome and Sanity

7 replies
Last updated: Jun 2, 2021
I use Gridsome to build static pages with Sanity as the source. In my building used https://www.sanity.io/docs/image-url to load images. I also use vue-lazyload.
I would like a placeholder the same size as the picture before the picture is finished loading. The width is usually 100% of the container. But the height of the image is dynamic.

Is there any possibility to extract the height of the image before the image is loaded?
Jun 2, 2021, 6:09 AM
If you know the image URL then sanity images always have the image size in the url. e.g.
<https://cdn.sanity.io/images/{projectid}/{dataset}/{hash}-6720x4480.jpg>
Jun 2, 2021, 6:12 AM
Great, I have not noticed that the size of the image is part of the image name. It can solve my challenge with reflow.
Thanks!
Jun 2, 2021, 6:15 AM
you can also GROQ the metadata like image width/height/aspectRatio https://www.sanity.io/docs/image-type#df3f768ce073

"metadata": {
    "dimensions": {
      "aspectRatio": 1.000733137829912,
      "height": 1364,
      "width": 1365
    },
...
Jun 2, 2021, 6:16 AM
probably a nicer way of doing it
Jun 2, 2021, 6:17 AM
I was looking at that but didn’t know how 🙂
Jun 2, 2021, 6:17 AM
always fun to poke around in the image asset properties with Vision

*[_type == "sanity.imageAsset" ] { 
    metadata { 
        dimensions
    }
}[0]

Jun 2, 2021, 6:21 AM
A follow-up question: I made it work for a photo field. I also have a text field (_rawBody). How can I change the query so that images included in the text field also include metadata?
I use the Sanity Gridsome template
https://www.sanity.io/create?template=sanity-io/sanity-template-gridsome-blog if it is helpful to know.
Jun 2, 2021, 11:50 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?