CSS/js异步加载CSS

来自康健生活
< CSS
Kangkk​(留言 | 贡献)2020年7月20日 (一) 06:19的版本 (创建页面,内容为“== 引言 == 在 head 标签中插入 js 代码异步加载 CSS,以此规避 <syntaxhighlight lang="css"> <link rel="stylesheet" href="***.css"></syntaxhighlight>…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

引言

在 head 标签中插入 js 代码异步加载 CSS,以此规避

<link rel="stylesheet" href="***.css">

加载过程中阻塞渲染的问题(在 css 全部加载之前,会有一段时间“白屏”)。

  <script>
    // https://github.com/filamentgroup/loadCSS
    !function(e){"use strict"
    var n=function(n,t,o){function i(e){return f.body?e():void setTimeout(function(){i(e)})}var d,r,a,l,f=e.document,s=f.createElement("link"),u=o||"all"
    return t?d=t:(r=(f.body||f.getElementsByTagName("head")[0]).childNodes,d=r[r.length-1]),a=f.styleSheets,s.rel="stylesheet",s.href=n,s.media="only x",i(function(){d.parentNode.insertBefore(s,t?d:d.nextSibling)}),l=function(e){for(var n=s.href,t=a.length;t--;)if(a[t].href===n)return e()
    setTimeout(function(){l(e)})},s.addEventListener&&s.addEventListener("load",function(){this.media=u}),s.onloadcssdefined=l,l(function(){s.media!==u&&(s.media=u)}),s}
    "undefined"!=typeof exports?exports.loadCSS=n:e.loadCSS=n}("undefined"!=typeof global?global:this)

loadCSS("***.css");
  </script>