Asynchronously loading CSS is mainly used for performance optimization
1. Why do performance optimization
CSS is mainly used for page rendering and content display. All CSS affects the user's first experience of the website, so CSS needs to be optimized
2. Implementation of asynchronously loading css
link
Insert the tag athead
the end of the tag using js
// 创建link标签
const myCSS = document.createElement( "link" );
myCSS.rel = "stylesheet";
myCSS.href = "mystyles.css";
// 插入到header的最后位置
document.head.insertBefore( myCSS, document.head.childNodes[ document.head.childNodes.length - 1 ].nextSibling );
link
If the tagmedia
attribute is set tonoexis
, the browser will think that the current style sheet is not applicable to the current type, and will download it without blocking page rendering. After the loading is complete, setmedia
the value ofscreen
orall
to let the browser start parsing CSS
<link rel="stylesheet" href="mystyles.css" media="noexist" onload="this.media='all'">
- Marking the link element as an alternate optional style sheet through the rel attribute can also achieve asynchronous loading by the browser. Also don't forget to set rel back to stylesheet after loading is complete
<link rel="alternate stylesheet" href="mystyles.css" onload="this.rel='stylesheet'">