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.
- Combine multiple CSS and JavaScript files into a single file.
- Use CSS sprites to reduce image requests.
- Minimize inline styles and scripts.
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:
- Using the correct image format (JPEG for photos, PNG for transparency, SVG for icons).
- Compressing images using tools like TinyPNG or ImageOptim.
- Using responsive images with the
srcsetattribute.
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.
- Use tools like UglifyJS for JavaScript and CSSNano for CSS.
- Enable Gzip or Brotli compression on the server.
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
- Use
asyncordeferfor non-blocking scripts. - Place scripts at the bottom of the page.
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:
- Reducing HTTP requests
- Optimizing images
- Minifying and compressing files
- Leveraging browser caching
- Loading JavaScript efficiently
- Using a CDN