3.5 Hours

8. Asset Optimization: Images, Fonts, and CSS

Optimization

Assets like images, fonts, and CSS can significantly impact load times. This module covers techniques for optimizing assets in your build pipeline. Understanding asset optimization is essential for building fast applications.

The key insight is that assets are often the biggest part of the bundle. Images can be compressed, fonts can be subset, and CSS can be optimized. This module covers techniques for each type of asset. Understanding asset optimization is essential for production performance.

This module covers image optimization, font loading, CSS optimization, and asset caching.

Image Optimization

Image optimization techniques include: compression (reducing file size), responsive images (serving different sizes), lazy loading (loading images on demand), modern formats (WebP, AVIF), and using CDNs. These techniques dramatically reduce image load times.

Tools like imagemin, sharp, and svgo can automate image optimization. Vite has built-in image optimization with plugins. Webpack can use image-loader or url-loader. Understanding image optimization is essential for fast applications.

Font Optimization

Font optimization techniques include: font subsetting (including only used characters), preloading (loading fonts early), font-display (controlling how fonts render), and using system fonts as fallbacks. These techniques improve perceived performance.

Fonts are often large and can delay rendering. Subsetting reduces font size by 50-90%. Preloading ensures fonts are available when needed. Understanding font optimization is essential for fast applications.

JavaScript
// Vite asset optimization
// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  // Image optimization with imagemin
  build: {
    rollupOptions: {
      plugins: [
        // imagemin plugin
      ],
    },
  },
});

// Webpack image optimization
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024, // Inline small images as data URLs
          },
        },
      },
    ],
  },
};

// CSS optimization
// Use mini-css-extract-plugin for production
// Use cssnano for minification
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  require('cssnano')({
                    preset: 'default',
                  }),
                ],
              },
            },
          },
        ],
      },
    ],
  },
};

// Responsive images
// src/components/Image.jsx
import { useState, useEffect } from 'react';

export function Image({ src, alt, sizes = '100vw' }) {
  const [loaded, setLoaded] = useState(false);
  
  return (
    <img
      src={src}
      alt={alt}
      sizes={sizes}
      srcSet={`
        ${src}?w=320 320w,
        ${src}?w=640 640w,
        ${src}?w=1024 1024w,
        ${src}?w=2048 2048w
      `}
      loading="lazy"
      onLoad={() => setLoaded(true)}
      style={{ opacity: loaded ? 1 : 0, transition: 'opacity 0.3s' }}
    />
  );
}

Try It Yourself: Asset Optimization

Follow these steps to optimize assets.

Step 1: Install optimization tools
npm install --save-dev imagemin imagemin-webp sharp<br>npm install --save-dev postcss cssnano

Step 2: Configure image optimization
Add image optimization to your build process.

Step 3: Configure CSS optimization
Add PostCSS and cssnano for CSS minification.

Step 4: Test the results
Compare bundle sizes before and after optimization. Use Lighthouse to measure performance.

Try It Yourself: Optimize images in your project. Implement lazy loading. Test with WebPageTest or Lighthouse.

Knowledge Check

Ready to test your understanding of 8. Asset Optimization: Images, Fonts, and CSS?

Back