I. Questions & Conclusions
1. Does CSS loading block parse rendering of the DOM tree?
- CSS does not block parsing of the DOM tree
- CSS blocks dom tree rendering
2. Does CSS loading block JS running?
- CSS loading blocks the execution of subsequent JS statements
Second, the results and optimization plan
1. The result
- Slow loading of the CSS results in a long blank screen
2. Optimization scheme
-
- CDN acceleration: CDN will select the nearest node with cached content to provide resources according to the network condition and reduce the loading time
-
- Compress the CSS: Use the webpack and gulp packaging tools to enable Gzip compression
-
- Rational use of caching: strong caching, negotiated caching and other strategies
- Reduce THE number of HTTP requests, merge CSS files, or simply write them inline (cons: no caching)
Three, principle analysis
1. The rendering process of the browser is as follows:
2. The conclusions are as follows:
- DOM parsing and CSS parsing are independent and parallel, so CSS loading does not block DOM parsing
- Since the Render Tree is dependent on the DOM Tree and CSSOM Tree, he must wait until the CSSOM Tree is built, i.e. the CSS resource is loaded (or the CSS resource fails to load), before he can start rendering. Therefore, CSS loading blocks Dom rendering
- Because JS may manipulate previous Dom nodes and CSS styles, browsers maintain the order of CSS and JS in HTML. Therefore, the stylesheet will be loaded and executed before any subsequent JS is executed. So CSS blocks subsequent JS execution
Four, the actual scene
1. Two events for page loading
- OnLoad: this function is triggered only after all resources on the page have been loaded, such as CSS, JS, images and videos
- DOMContentLoaded: This event is triggered when the content of the page has been parsed
2. Impact of CSS loading
- If both CSS and JS exist on the page, and js exists behind the CSS, the DOMContentLoaded event is executed after the CSS is loaded
- In other cases, DOMContentLoaded does not wait for CSS to load, and the DOMContentLoaded event does not wait for images, videos, and other resources to load
The original article is demonstrated by examples, click here to jump