Comprehensive, actionable guidelines for delivering fast, responsive, and accessible images on the web.
Your website's images are quietly destroying your performance scores and user experience. Every unoptimized image costs you visitors, conversions, and search rankings. But here's the reality: most developers are still serving bloated JPEGs in 2024 when they could deliver AVIF files that are 50% smaller with better quality.
Every second matters. Research shows that a 100ms delay in page load time can hurt conversion rates by 7%. Yet the average webpage loads 21 images totaling 1.7MB. That's not just slow—it's expensive.
Common image performance killers:
These Cursor Rules transform your development workflow with battle-tested patterns for delivering fast, responsive images across every device and browser. You'll implement modern formats, responsive delivery, and performance optimizations that actually move your Lighthouse scores.
Modern Format Support: Automatic AVIF/WebP delivery with intelligent fallbacks that work across all browsers—no more "format not supported" issues.
Responsive Image Mastery: Complete srcset and <picture> implementations that serve device-appropriate sizes, not oversized desktop images to mobile users.
Performance-First Patterns: Lazy loading, preloading strategies, and layout shift prevention that improve Core Web Vitals scores.
Framework Integration: Ready-to-use configurations for Next.js, WordPress, Gatsby, and vanilla HTML that work out of the box.
50% smaller file sizes with AVIF format adoption while maintaining visual quality
3x faster page loads through proper lazy loading and responsive image delivery
90+ Lighthouse scores with automated compression and modern format serving
Zero layout shift with proper width/height declarations and placeholder strategies
<!-- What you probably do now -->
<img src="hero-large.jpg" alt="Team photo" style="width: 100%;">
<!-- What you'll build with these rules -->
<picture>
<source type="image/avif" srcset="hero-320.avif 320w, hero-640.avif 640w, hero-1200.avif 1200w">
<source type="image/webp" srcset="hero-320.webp 320w, hero-640.webp 640w, hero-1200.webp 1200w">
<img src="hero-640.jpg"
srcset="hero-320.jpg 320w, hero-640.jpg 640w, hero-1200.jpg 1200w"
sizes="(max-width: 640px) 100vw, (max-width: 1200px) 50vw, 33vw"
width="1200" height="800"
alt="Development team collaborating in modern office space"
loading="lazy" decoding="async">
</picture>
Instead of manually optimizing every image upload, you'll configure automatic processing:
// Auto-enabled with these rules
add_theme_support('responsive-images');
add_filter('wp_generate_attachment_metadata', 'generate_webp_avif_variants');
Your workflow becomes: upload → automatic optimization → responsive delivery. No manual intervention required.
Transform your component patterns:
// Old approach
<img src="/hero.jpg" alt="Hero image" />
// Optimized with rules
<Image
src="/hero.jpg"
alt="Hero showcasing product features"
width={1200}
height={800}
priority
placeholder="blur"
sizes="(max-width: 768px) 100vw, 50vw"
/>
Copy the provided Cursor Rules configuration into your .cursorrules file. The rules immediately enhance your editor with intelligent image optimization patterns.
# Add to your package.json scripts
"optimize-images": "npx @squoosh/cli \"src/images/*.{png,jpg}\" --avif --webp --mozjpeg"
Use the provided <picture> element template as your default image implementation. The rules will guide you through proper srcset, sizes, and fallback configurations.
Set up the webpack configuration provided in the rules to automatically process images during build. Your images get optimized without manual intervention.
npm run lighthouse # Automated performance testing
The rules include testing patterns that enforce performance thresholds in your CI pipeline.
Week 1: Implement modern format delivery and see immediate file size reductions of 30-50% with AVIF/WebP adoption.
Week 2: Deploy responsive images and eliminate mobile users downloading desktop-sized files. Mobile performance scores jump 20-30 points.
Month 1: Complete workflow integration means every new image automatically gets optimized. Your performance scores consistently stay above 90.
Ongoing: Automated CI checks prevent performance regressions. New team members follow the same optimization patterns automatically.
Your images will load faster, look better, and cost less to deliver. These rules give you the complete toolkit to optimize web images like a performance expert—without the years of trial and error.
Ready to transform your image delivery? Implement these rules and watch your performance scores soar.
You are an expert in image optimization for web performance using HTML, CSS, JavaScript, modern image formats (WebP, AVIF), CDNs, and WordPress.
Key Principles
- Always deliver the smallest acceptable file that meets visual requirements.
- Prefer modern formats (AVIF > WebP > JPEG/PNG); provide graceful fallbacks.
- Serve device-appropriate sizes with `srcset`, `sizes`, and `<picture>` art-direction.
- Lazy-load all below-the-fold imagery using `loading="lazy"` or Intersection Observer.
- Prevent layout shift by providing explicit `width` and `height`.
- Automate compression, conversion, and delivery via build tools or CDN.
- Preserve accessibility and SEO with descriptive filenames and meaningful `alt` text.
HTML
- Default pattern:
```html
<picture>
<source type="image/avif" srcset="hero.avif 1x, [email protected] 2x"/>
<source type="image/webp" srcset="hero.webp 1x, [email protected] 2x"/>
<img src="hero.jpg" srcset="hero.jpg 1x, [email protected] 2x" width="1200" height="800" alt="Team collaborating in open office" loading="lazy" decoding="async"/>
</picture>
```
- Inline SVGs < 4 KB directly in markup; otherwise treat as external images.
- Declare `role="presentation"` and empty `alt` for purely decorative images.
CSS
- `img {max-width:100%; height:auto;}` for responsive scaling.
- Use `object-fit:cover;` in cards or grids to avoid aspect-ratio distortion.
JavaScript
- Rely on native lazy loading; feature-detect and polyfill only for browsers < Chrome 76.
- Preload largest, above-the-fold asset:
```html
<link rel="preload" as="image" href="hero.avif" imagesrcset="hero.avif 1x, [email protected] 2x" imagesizes="100vw"/>
```
- Prefer build-time optimization (webpack/rollup) over runtime manipulation.
File & Alt Naming
- Filenames: lowercase-hyphenated-keywords ("golden-gate-bridge-sunset.webp").
- `alt`: concise, purpose-driven description; avoid "image of" redundancy.
Error Handling & Validation
- Fallback chain: AVIF → WebP → JPEG/PNG within `<picture>`.
- Add runtime fallback:
```html
<img src="hero.webp" onerror="this.onerror=null;this.src='hero-fallback.jpg';" alt="…"/>
```
- CI script: fail build if > 1 MB hero or > 300 KB standard image after compression.
- Strip EXIF & IPTC metadata to shrink size and guard privacy.
WordPress
- Install Imagify or ShortPixel; enable "lossy" ≤ 85 quality and automatic WebP/AVIF conversion.
- Activate `add_theme_support('responsive-embeds');` to ensure `srcset` generation.
- Offload originals to CDN (Cloudflare Images, WP Offload Media) with on-the-fly resizing.
Next.js
- Use built-in `<Image>` component:
```tsx
import Image from 'next/image';
<Image src="/hero.jpg" alt="Team collaborating" width={1200} height={800} priority placeholder="blur" />
```
- `next.config.js`:
```js
module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
deviceSizes: [320,640,750,828,1080,1200],
domains: ['cdn.example.com']
}
}
```
Gatsby
- Configure `gatsby-plugin-image`:
```js
{
resolve: 'gatsby-plugin-image',
options: {
quality: 80,
formats: ['auto','webp','avif']
}
}
```
- Prefer `StaticImage` for build-time generation; use `GatsbyImage` for GraphQL-sourced media.
Testing
- Add `npm run lighthouse` to CI; enforce ≥ 90 Performance score.
- Use `npx @squoosh/cli "*.{png,jpg}" --avif --webp --mozjpeg` during pre-commit.
- Validate lazy loading via Puppeteer:
```js
const lazyCount = await page.$$eval('img[loading="lazy"]', els => els.length);
if(lazyCount / await page.$$eval('img', els => els.length) < 0.9) throw 'Lazy loading coverage too low';
```
Performance
- Inline critical LCP image as Base64 placeholder or blur-up.
- Defer CSS background images via class toggling after main content paint.
- Route all requests through HTTPS CDN with automatic Accept header negotiation.
Security
- Enforce Content Security Policy: `img-src https: data:`.
- Strip geo-location metadata to avoid leaking sensitive info.
Edge Cases & Pitfalls
- Safari ≤ 13: no WebP; ensure JPEG/PNG fallback.
- Don’t lazy-load first-viewport images; it delays Largest Contentful Paint.
- Match `sizes` attribute to actual CSS breakpoints; mismatches negate `srcset` gains.
Directory Structure Example
```
assets/
images/
originals/ # untouched design files
optimized/ # build-step output
hero.avif
hero.webp
hero.jpg
```
Automation Snippet (webpack)
```js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g)$/i,
type: 'asset',
parser: { dataUrlCondition: { maxSize: 4 * 1024 } },
use: [
{
loader: 'image-webpack-loader',
options: {
mozjpeg: { progressive: true, quality: 80 },
webp: { quality: 80 },
avif: { quality: 50 },
}
}
]
}
]
}
};
```
By consistently applying these rules, teams can achieve faster page loads, better Lighthouse scores, and an accessible, SEO-friendly user experience.