Will CSS loading cause blocking? Will CSS loading block JS running?

Time:2022-6-10

Direct conclusion:
1. CSS does not block DOM tree parsing
2. CSS loading blocks DOM tree rendering
3. CSS loading will block the execution of the following JS statements

In order to avoid too long white screen time, we should improve the CSS loading speed as much as possible. There are several optimization methods:

1. Use CDN (because CDN will select the nearest node with cached content to provide resources for you according to your network conditions, so the loading time can be reduced)
2. Compress CSS (you can use many packaging tools, such as webpack and gulp, or you can enable gzip compression)
3. Reasonably use the cache (setting cache control, expires, and e-tag is good, but one thing to note is that after the file is updated, you should avoid the impact of the cache. One of the solutions is to add a version number after the file name)
4. Reduce the number of HTTP requests, merge multiple CSS files, or simply write the inline style (one disadvantage of the inline style is that it cannot be cached)

About domcontentloaded:
For browsers, there are two main events for page loading: domcontentloaded and onload. Onload has nothing to say. It will be triggered only after all the resources on the page are loaded, including CSS, JS, images and videos.

1. If both CSS and JS exist in the page, and JS exists after CSS, the domcontentloaded event will be executed after the CSS is loaded.
2. In other cases, domcontentloaded does not wait for CSS to load, and domcontentloaded events do not wait for images, videos and other resources to load.

Reference from:
https://juejin.cn/post/6844903667733118983