Load css asynchronously

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

  • linkInsert the tag at headthe 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 );
  • linkIf the tag mediaattribute is set to noexis, 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, set mediathe value of screenor allto 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'">

Guess you like

Origin blog.csdn.net/weixin_65565362/article/details/127423388