Slow loading images? Ain't nobody got time for that - 🥷🏾! We certainly didn't. That's why we cooked up a script that turns hefty image files into sleek speed demons! Get ready to see some serious image optimization magic unfold - 🪄.
Our website was lit... but it was crawling
We recently launched a new website, and the team page looked great… except it was taking forever to load. Turns out, those high-resolution headshots, while looking sharp, were each clocking in at several megabytes. It wasn't just the team page, carousel images were also suffering the same fate. We're talking about a serious website performance problem here. 🐢 We knew we needed to do something about it - and fast! High-res is great, but not when it's making our website drag its feet.
From Slowpoke Rodriguez to Speedy Gonzales
Here's the practical solution we implemented: A script, engineered to handle those hefty images (we're talking JPEGs, PNGs, the whole gang!!!), shrink them down into perfectly optimized WebP versions, and save us from the sluggish website experience. How does it do this you ask?
Well firstly, we are using the sharp package. This is a super powerful image processing library for Node.js. Secondly, this script checks whether each image has been modified recently or not. If it has, the image gets the treatment!🥊If not, it just skips it. This is to save time and resources, not to mention that it adds a little bit of smarts to the code. This script is designed to be flexible, it knows what to do depending on what we tell it to optimize (team headshots, or carousel images).
Here’s a peek at the code, along with a breakdown:
Decoding the code
const sharp = require('sharp');: This line imports the Sharp library, our primary tool for manipulating images.const fs = require('fs');andconst path = require('path');: These lines import Node.js modules for working with the file system and handling file paths.const type = process.argv[2];: This retrieves the command-line argument that specifies which images to optimize (e.g., 'team' or 'carousel').
Next, the code validates the input. If it's invalid, the program exits.
It then defines a variable that holds the configuration for the requested optimization.
async function optimizeImage(inputPath, outputPath, options): This is the main function for processing each image.
First, it checks whether an optimized version of the image already exists and if it has been modified since the original. If optimization is needed, Sharp resizes the image to the specified dimensions (using the cover fit method, though other options like contain or fill are available).
The image is then converted to the WebP format with 80% quality, striking a good balance between size and visual fidelity. After processing, it logs the original size, optimized size, and the percentage reduction.
async function processImages(): This function sets up the entire process.
It checks if the specified input directory exists. If not, it exits. If the output directory doesn't exist, it creates one.
It logs the input and output paths in use. Then, it loops through the files in the input directory, checks if each file is the correct type, and calls the optimizeImage function with the appropriate paths and configurations.
processImages().catch(console.error);: This initiates the image processing and catches any errors that may arise.
How to run it
First, ensure that you have Node.js and npm (or yarn) installed, and that the script is saved on your machine—let’s assume it’s named optimize-images.js. Next, install the Sharp package by running npm install sharp in your project directory.
Run the script from the terminal as shown below:
A sidenote
To run this script you will need to add "optimize-images": "node optimize-images.js" into your package.json file.
That's all folks
The results were astonishing! We managed to shrink down the file size of an image from 7.9MB to just 21KB. That's a reduction of over 99%! This was typical of most images, and the improvement was immediately noticeable as the page loading became significantly faster. Plus, this process didn’t result in a loss of quality that was noticeable to the naked eye. This is the magic of image optimization.
Optimizing images is a game-changer for web performance. This script using JavaScript and Sharp can take those bloated images, and compress them to a fraction of their size, meaning faster loading websites and happier users. It's a win-win! So, what other optimizations are you using? Leave a comment below, and let's swap tips besties !!! 🥺