Chapter 15: HTML Performance Optimization

15.1 Introduction

Performance optimization is crucial for creating fast and efficient web pages. Optimized websites load quickly, reduce server load, and provide a better user experience.

15.2 Minimize HTTP Requests

Reducing the number of HTTP requests speeds up page load times.

Example: Combining CSS Files

    <!-- Instead of multiple stylesheets -->
    <link rel="stylesheet" href="style1.css">
    <link rel="stylesheet" href="style2.css">

    <!-- Use a single combined file -->
    <link rel="stylesheet" href="styles.min.css">
        

15.3 Optimize Images

Large images slow down websites. Optimize them by:

Example: Responsive Images

    <img src="small.jpg" srcset="medium.jpg 600w, large.jpg 1200w" alt="Optimized Image">
        

15.4 Minify and Compress Files

Minify CSS, JavaScript, and HTML files to reduce file size.

Example: Minified JavaScript

    // Before
    function greet() {
        console.log("Hello, World!");
    }

    // After minification
    function greet(){console.log("Hello, World!");}
        

15.5 Use Browser Caching

Leverage browser caching to store static resources like CSS, JS, and images.

Example: Setting Cache Headers in .htaccess

    <IfModule mod_expires.c>
        ExpiresActive On
        ExpiresByType image/jpg "access plus 1 year"
        ExpiresByType image/png "access plus 1 year"
        ExpiresByType text/css "access plus 1 month"
        ExpiresByType application/javascript "access plus 1 month"
    </IfModule>
        

15.6 Load JavaScript Efficiently

Example: Using Defer

    <script src="script.js" defer></script>
        

15.7 Use a Content Delivery Network (CDN)

CDNs store copies of your files on multiple servers worldwide, reducing latency.

Example: Using a CDN for jQuery

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        

15.8 Summary

In this chapter, we covered: