DEV Community

Cover image for Download only the pixels you need : image scaling with imagekit
Puka Tchou
Puka Tchou

Posted on

Download only the pixels you need : image scaling with imagekit

In 10 years, the weight of images on the web has increased by 194% on desktop and 500% (!) on mobile. The size and quantity of images you serve, whether on your portfolio or your professional projects, has most certainly followed the same curve.

Image size evolution since 2021

Furthermore, you have certainly sized your images to look perfect on your FHD or even 4k screen, which contributes to increasing their weight unnecessarily. And Google points this out to you in every pagespeed report: Properly size images

Pagespeed report

Well, using imagekit and a bit of JS, you can accomplish just that. Our goal will be to use imagekit's on-the-fly resizing capabilities to resize all the images used on our website before they are served to the final user.

First, you will need to create an imagekit free account. Once that's done, add an external storage location and configure the base URL to point to your website. Finally, you need to find your URL endpoint and copy it as we will need it for our snippet of code:

// we listen for the readystatechange event
document.addEventListener("readystatechange", () => {
  // "interactive" fires when the DOM is ready but the additional content has not been downloaded yet
  if (document.readyState === "interactive") {
    // we get all the images in the document
    document.querySelectorAll("img").forEach((img) => {
      img.dataset.oldSrc = img.src;
      // we remove the base of the URL from the image source
      const src = img.src.replace(window.location.origin, "");
      // we get the dimensions of the image
      const renderedWidth = img.scrollWidth;
      const renderedHeight = img.scrollHeight;
      // write your URL endpoint here
      img.src = `https://ik.imagekit.io/CHANGEME/tr:w-${renderedWidth},h-${renderedHeight}${src}`;
      // if the image returns an error (404 eg.), we revert back the origin
      img.onerror = () => {
        img.src = img.dataset.oldSrc;
        img.dataset.oldSrc = "";
      };
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

That's it!

Top comments (0)