Improving web performance: Strategies and Tips for Inlining Key CSSs
This article explores ways to inline key CSS (embed CSS rules directly into HTML documents) to optimize website performance. By inlining critical CSS, web rendering can be significantly accelerated, especially the loading of first-screen content, avoiding rendering delays caused by additional HTTP requests to obtain external CSS files.
Key points:
- Precisely identify key CSS: Critical CSS refers to the minimum CSS code required to render the content on the first screen. This varies from page to page and requires recognition and extraction with tools such as Google PageSpeed ??Insights, Critical Path CSS Generator, and Penthouse.js.
- Trial-offs: Inline critical CSS can improve loading speeds, but also increase HTML document size and can cause code redundancy (especially when the same CSS rules are reused on multiple pages). Therefore, it is important to make sure that inlined CSS is indeed crucial to the web page.
- Automation Tools: Tools such as Grunt, npm modules (such as Critical), Gulp, and WordPress plug-ins (such as Autoptimize, Above The Fold Optimization, and W3 Total Cache) can automatically identify, extract and inline keys. CSS, simplify operation process.
In the early days of the Internet, websites mainly displayed text information. With the increase in network speed, users can quickly download high-definition pictures and videos, and the website functions are becoming increasingly complex, using various CSS and JavaScript frameworks, plug-ins, etc. Loading all necessary files takes time, and faster websites lead to better user experience, which is crucial for website success. Inlining critical CSS and loading non-critical CSS asynchronously is a key strategy for improving performance.
What is the key CSS?
Key CSS refers to CSS code used to style content on the homepage (the first part of the user sees, including navigation and other elements). It is crucial to quickly render the content on the first screen.
It should be noted that users use various devices and windows to access the website, so considering the content on the home screen is not enough to solve all problems. CSS related to basic layout and typography should also be considered as critical CSS.
Modern Web Development Practice Recommends Inline CSS, For example:
<!DOCTYPE html> <html> <head> <title>優(yōu)化后的網(wǎng)頁(yè)</title> <style type="text/css"> /* 你的最小化關(guān)鍵 CSS 代碼 */ </style> </head> <body> <!-- 你的標(biāo)記 --> </body> </html>
Why do you need to inline?
Tools such as Google PageSpeed ??Insights may prompt for optimization of CSS loading, suggesting inline critical CSS and asynchronously loading blocking rendered stylesheets.
The browser will only render the content on the homepage after all CSS files are loaded. This becomes a bottleneck when a large number of files need to be loaded. Not all users have high-speed network connections, and it can be frustrating to wait for libraries, CSS, and JavaScript to load before the content is loaded. Even high-speed network users may lose connections in some cases (such as through tunnels). If the website has inlined the critical CSS and no other files are loaded before the main content is displayed, the user will still be able to access the main content even in the event of a broken connection.
The following figure shows the difference between a normal web page and an optimized web page: the optimized version allows users to access content approximately 0.5 seconds in advance. Improvements will be more obvious when a large number of additional libraries need to be loaded.
Should key CSS be inlined?
It depends on the situation. If you are not using any large frameworks or libraries and your own CSS file size is also small, you may not need to inline CSS.
If you use frames such as Bootstrap, all the functions of the frame may not be used. In this case, you can extract only the critical CSS from the framework stylesheet and load the actual framework asynchronously. This will significantly increase the speed of the website.
Inline stylesheets can be cached, while HTML is not usually cached (this is not usually recommended!). This means there are sometimes differences between the two. Keep this in mind when making updates! Additionally, inline CSS causes page size to increase each time a user loads a website. For example, if a website has 30kB of inline CSS per page, a single user will consume 300kB for 10 page views. This may not sound like a big deal, but in some parts of the world (and in some 3G/4G data plans), data is expensive. Make sure that the CSS you plan to inline is really critical to your page and don't inline everything.
(The following content is similar to the original text. To avoid duplication, detailed steps on how to find the key CSS, use Grunt, npm modules, Gulp and other tools, and the final FAQ section are omitted. These can Found through the original text. )
Summary
Whether to inline the critical CSS depends on the user's access pattern and website structure. If your site is a single page website, visitors won't access it frequently, or if you have a complex website with frameworks and plugins, inline critical CSS can significantly improve performance.
The only concern with inline CSS is that it increases the page size per visit. This can be mitigated by using cookies, sending critical CSS only on the first visit, while still loading and cacheing the full CSS file asynchronously. This is a bit complicated, but you can get the best of both worlds at the same time.
The above is the detailed content of How and Why You Should Inline Your Critical CSS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
