nuxt / image

Plug-and-play image optimization for Nuxt applications.
https://image.nuxt.com
MIT License
1.34k stars 270 forks source link

Image size detection for CSR #106

Open farnabaz opened 3 years ago

farnabaz commented 3 years ago

Detecting image size has benefits on server-side rendering and prevent CLS for server-rendered pages. But it seems tricky and inefficient when it comes to client-side rendering.

/cc @Atinux @pi0

farnabaz commented 3 years ago

Current state:

retroriff commented 3 years ago

Is there any solution so the <img> tag includes width and height attributes?

stuible commented 3 years ago

Would love this as well!

stuible commented 3 years ago

Any updates on this feature request? This is absolutely essential for modern web development, IMO.

stuible commented 3 years ago

I've come up with a interim solution for statically generated Nuxt sites. It's kind of terrible but it does work (Isn't this always the case?). I require a node library called image-size (after checking to make it's running server side and NOT client side) that reads the images dimensions and stores them in an array which Nuxt serializes and makes available to the client once generated.


async asyncData({ $content, params }) {

    const images = await $content('images').fetch();

    // generate array of image dimensions
    const dimensions = [];

    if (process.server) {
      const sizeOf = require('image-size');
      images.forEach((image) => {
        console.log(image);
        const sizeOfResult = image ? sizeOf(`static${image}`) : {};
        dimensions.push({
          ...sizeOfResult,
          slug: image,
        });
      });
    }

     return {
          images,
          dimensions
     } 
}

I can then access these dimensions in my template like so:

<nuxt-picture
       :src="image[0]"
       :width="dimensions.find(x => x.slug == image[0]).width"
       :height="dimensions.find(x => x.slug == image[0]).height"
     />

One important caveat: since the Nuxt dev server runs asyncData() on the client side when you navigate between routes, the width and height will not be populated when developing. They will however, be populated on your statically generated, production site. A fresh load of the webpage while developing will also load the correct dimensions.