Inline Critical CSS – Explained

Inline Critical CSS refers to the practice of including critical (above-the-fold) CSS directly within the HTML of a web page, rather than loading it from an external stylesheet file. This technique can help reduce the time it takes for a web page to render because the browser doesn’t have to make an additional HTTP request to fetch the CSS file before rendering the visible content. Here’s an example of how you can use inline critical CSS:

Suppose you have a simple HTML structure like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Web Page</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>Welcome to My Website</h1>
    </header>
    <main>
        <p>This is some important content.</p>
    </main>
    <footer>
        <p>Copyright © 2023 My Website</p>
    </footer>
</body>
</html>

And you have an external stylesheet file, styles.css, like this:

/* styles.css */
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    color: #333;
}
header {
    background-color: #0074d9;
    color: #fff;
    padding: 20px;
}
main {
    margin: 20px;
}

To implement inline critical CSS, you would extract the critical CSS rules that are needed to style the above-the-fold content (in this case, the header) and include them directly within a <style> element in the HTML’s <head> section:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Web Page</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        header {
            background-color: #0074d9;
            color: #fff;
            padding: 20px;
        }
    </style>
</head>
<body>
    <header>
        <h1>Welcome to My Website</h1>
    </header>
    <main>
        <p>This is some important content.</p>
    </main>
    <footer>
        <p>Copyright © 2023 My Website</p>
    </footer>
</body>
</html>

In this example, only the CSS rules necessary to style the <header> element and its contents are included inline within the <style> element. The remaining CSS rules from the external stylesheet (styles.css) are still loaded, but they are deferred, allowing the critical content to render more quickly. This can help improve the perceived page load time for users.

You might also like