Optimize images for web (format, size, lazy load)
✓Works with OpenClaudeYou are a web performance specialist. The user wants to optimize images for web delivery by converting formats, reducing file sizes, and implementing lazy loading.
What to check first
- Run
npm list sharpornpm list imageminto see if image processing libraries are installed - Check your
package.jsonto see current dependencies for image handling - Verify your HTML has
<img>tags you want to optimize and lazy load
Steps
- Install Sharp (Node.js image processor) or ImageMagick CLI:
npm install sharpfor programmatic optimization - Create a build script that converts images to WebP and AVIF formats alongside original JPG/PNG using Sharp's
.toFormat()method - Add width and height attributes to
<img>tags to prevent layout shift:<img src="image.jpg" width="800" height="600" alt="..."> - Implement the
<picture>element with multiple source formats ordered by efficiency: WebP first, then AVIF, fallback to JPG - Add
loading="lazy"attribute to images below the fold:<img src="image.jpg" loading="lazy" alt="..."> - Use
srcsetwith responsive image sizes:srcset="image-400w.jpg 400w, image-800w.jpg 800w, image-1200w.jpg 1200w" - Set explicit
sizesattribute for responsive images:sizes="(max-width: 600px) 100vw, 50vw" - Run optimization script during build to compress images via Sharp's
.jpeg({quality: 80})or.webp({quality: 80})
Code
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const imageDir = './images';
const outputDir = './images/optimized';
// Create output directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
async function optimizeImage(inputPath) {
const filename = path.parse(inputPath).name;
const basePath = path.join(outputDir, filename);
try {
// Generate WebP version (best compression)
await sharp(inputPath)
.resize(1920, 1920, { withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(`${basePath}.webp`);
// Generate AVIF version (next-gen format)
await sharp(inputPath)
.resize(1920, 1920, { withoutEnlargement: true })
.avif({ quality: 75 })
.toFile(`${basePath}.avif`);
// Generate optimized JPG fallback
await sharp(inputPath)
.resize(1920, 1920, { withoutEnlargement: true })
.
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Performance Skills
Other Claude Code skills in the same category — free to download.
Bundle Analyzer
Analyze and reduce JavaScript bundle size
Code Splitting
Implement code splitting and dynamic imports
Caching Strategy
Design and implement caching strategy
Database Query Perf
Optimize database query performance
Render Optimizer
Optimize React re-renders and component performance
Lighthouse Fixer
Fix issues found in Lighthouse audit
Prefetch Setup
Set up resource prefetching and preloading
Tree Shaking Fix
Fix tree-shaking issues and reduce dead code
Want a Performance skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.