Lesson 19 / Performance

Image Optimization

Time
55 min
Type
Reading + Interactive
Level
Intermediate

Optimize image formats, sizes, compression, responsive delivery, and lazy loading for faster websites.

Teacher Notes / In-Class Use

Demo Live

  • Walk through the interactive demo before students start changing their own project files.
  • Connect the demo back to the first goal: Identify problematic images

Try In Class

  • Optimize three images for the web.
  • Have students make one visible change, save, refresh, and explain what changed.

Submit Or Check

  • Ask students to show the work in the browser, not only in the editor.
  • Have students commit their progress with a clear message when the checkpoint is stable.

Watch For

  • Students copying code without checking file paths, spelling, or capitalization.
  • Visual changes that work locally but break when the project is published.

Learning Goals

  • Identify problematic images
  • Choose appropriate formats and compression
  • Resize images to match their display dimensions
  • Use responsive image techniques and lazy loading

Interactive Demo

How to use this demo.

Use the demo as a small lab. Change one thing, observe the result, then connect it back to your own project.

What To Try

  • Change image format, width, loading behavior, and alt text.
  • Watch the estimated size and code sample update.

What Changes

  • Image choices affect performance, accessibility, and layout stability.
  • The code sample shows the markup decisions behind the preview.

What To Notice

  • Optimization is not only compression. It includes size, loading, dimensions, and text alternatives.
  • Alt text should communicate the image purpose in context.

Apply It

  • Pick one image in your project and verify its size, loading behavior, and alt text.

Interactive Demo

Image Optimization Lab

Change the format, displayed width, loading behavior, and alt text purpose. Watch how the markup and performance notes respond.

Preview 800w WebP
Optimized hero image with useful alt text.
Estimated file
160 KB
Selected source
800w
Loading
Lazy
<img
  src="campus-800.webp"
  srcset="campus-400.webp 400w, campus-800.webp 800w, campus-1200.webp 1200w"
  sizes="(max-width: 720px) 100vw, 720px"
  alt="Campus walkway at sunset"
  loading="lazy"
>

What to notice

  • Format affects file size, transparency support, and image quality.
  • Displayed width should guide the source sizes you export.
  • Lazy loading helps most when images start below the first screen.

Try this

  • Switch from WebP to PNG and compare the estimated file size.
  • Increase the display width and watch the selected source change.
  • Change the alt text purpose and explain which version fits the image.

This demo uses extra JavaScript for teaching. The code sample shows the pattern to practice. View full demo source (opens in a new tab).

Introduction

Image optimization is a critical aspect of web performance.

By optimizing images, you can significantly reduce page load times, improve user experience, and support stronger search engine performance.

Key Concepts

  • Identifying Problematic Images
  • Image Format
  • Image Size
  • Image Compression
  • Image Optimization Tools
  • Responsive Images
  • Lazy Loading

Identifying Problematic Images

Use browser developer tools and performance testing tools to find large and poorly optimized images.

  • Browser Developer Tools: Network and Performance tabs can locate large files and load bottlenecks.
  • Website Speed Testing Tools: WebPageTest and Google PageSpeed Insights can reveal performance issues.
  • Lighthouse: Audits image size issues, missing alt text, and other performance concerns.

Common Issues

  • Large file sizes
  • Unoptimized formats
  • Lack of compression
  • Missing or incorrect alt text

Choosing the Right Image Format

Each format serves specific needs. Choosing the right one helps balance quality, file size, transparency, and animation support.

  • JPEG: Great for photos. Uses lossy compression.
  • PNG: Ideal for images with sharp edges or transparency. Uses lossless compression.
  • GIF: Use for simple animations. Limited color palette.
  • WebP: Strong compression with transparency and animation support. Modern browser support required.

Resizing Images

Resize images to match their display dimensions.

Avoid upscaling and use tools like Photoshop, GIMP, TinyPNG, or Squoosh.

Compressing Images

Compression reduces image file size. The right compression method depends on the type of image and how much quality loss is acceptable.

Lossy Compression

Find the balance between quality and file size. Use progressive JPEG when appropriate.

// Photoshop: Save for Web, choose JPEG, adjust quality

Lossless Compression

Lossless compression is ideal for text, line art, and graphics with solid colors.

// Photoshop: Save for Web, choose PNG, adjust compression

Image Optimization Tools

  • Online: TinyPNG, Squoosh
  • Desktop: Photoshop, Photoshop Express
  • CLI: ImageMagick, OptiPNG

Advanced Techniques

Responsive images and lazy loading help deliver the right image at the right time.

Responsive Images: Adapting to Different Screens

Responsive images are a fundamental part of building performance-optimized, device-agnostic websites.

By tailoring image delivery based on the screen size and resolution of the user's device, you can ensure faster load times and improved visual quality without wasting bandwidth.

Key Techniques for Responsive Images

  • srcset Attribute
  • sizes Attribute
  • Picture Element

srcset Attribute

The srcset attribute allows developers to define multiple image sources for a single image element.

This enables the browser to choose the most appropriate image based on the device's screen width and resolution.

<img
  src="image-small.jpg"
  srcset="image-small.jpg 400w, image-medium.jpg 800w, image-large.jpg 1200w"
  sizes="(max-width: 768px) 400px, (max-width: 1024px) 800px, 1200px"
  alt="Image description"
>

sizes Attribute

The sizes attribute complements srcset by describing the display width of the image in different layout scenarios.

This allows the browser to better anticipate which image to download.

Picture Element

The picture element offers even more control, enabling developers to supply different image formats and resolutions based on media queries.

This is especially useful when combining modern formats like WebP with fallbacks.

<picture>
  <source media="(min-width: 768px)" srcset="image-large.jpg">
  <source media="(min-width: 480px)" srcset="image-medium.jpg">
  <img src="image-small.jpg" alt="Image description">
</picture>

Best Practices for Responsive Images

  • Optimize images for each screen size by resizing and compressing them appropriately.
  • Maintain a consistent naming scheme to keep your assets organized and manageable.
  • Regularly test responsive images on a range of devices to ensure visual quality and performance.

Lazy Loading Images: A Performance Boost

Lazy loading defers the loading of non-visible images until the user is likely to see them.

This conserves bandwidth, reduces initial page load time, and improves the overall experience, especially on long-scroll pages or mobile networks.

How Lazy Loading Works

  • A placeholder or empty space is initially shown in place of the full image.
  • As the user scrolls and the image nears the viewport, the actual image begins loading.
  • Once loaded, the placeholder is replaced, often using a fade-in or similar transition.

JavaScript-Based Lazy Loading

For greater customization or compatibility, JavaScript can be used to implement lazy loading.

This example uses the Intersection Observer API.

const images = document.querySelectorAll('img[data-src]');

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      observer.unobserve(img);
    }
  });
});

images.forEach((img) => observer.observe(img));

Browser-Native Lazy Loading

Modern browsers support native lazy loading with the loading="lazy" attribute on img tags.

<img src="image.jpg" alt="Image description" loading="lazy">

Benefits of Lazy Loading

  • Faster initial page rendering and perceived performance.
  • Reduced bandwidth usage and server load.
  • Enhanced user experience on slow or mobile networks.

To avoid layout shifts, use placeholder images or dimensions that match the aspect ratio of the final image. Test across devices and browsers to ensure consistency and performance.

Conclusion

By following these image optimization techniques, you can significantly improve your website's performance and user experience.

  • Image Format: Choose the right format based on content and quality needs.
  • Image Size: Match display dimensions and avoid upscaling.
  • Compression: Use lossy or lossless techniques as appropriate.
  • Responsive Images: Adapt to different screen sizes and resolutions.
  • Lazy Loading: Improve load times by deferring off-screen images.
  • WebP: Leverage modern formats for optimal compression.

Checkpoint

Before moving on, make sure these feel true.

  • I can explain the main concept in my own words.
  • I can apply this lesson to my current project.
  • I can verify the result in the browser.
  • I can commit the change with a clear message.

Project Connection

This lesson supports current class projects.

Practice

  • Optimize three images for the web.
  • Add responsive image attributes to one image.
  • Use loading="lazy" where appropriate.

Resources

  • Adobe Photoshop optimizing images
  • Adobe Photoshop optimizing images for JPEG format
  • Adobe Photoshop optimizing images for PNG format
  • MDN - Responsive Images
  • MDN - Lazy Loading