异步加载css文件

preload

都知道,stylesheets的加载会阻塞渲染,延迟页面展示,为了提高首屏渲染的加载速度,可以将非关键CSS延迟异步加载,<link rel=”preload”>提供了支持。其次,loadCSS(https://github.com/filamentgroup/loadCSS)提供`JavaScript Polyfill`以支持跨浏览器兼容。

1
2
3
4
5
<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="path/to/mystylesheet.css"></noscript>
/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
(function(){ ... }());
</script>

rel=preload,会让浏览器的主渲染机制介入前就进行预加载,但它载入后并不会被解析。load可以处理这个

1
<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.rel='stylesheet'">

loadCSS Funtion API

  • before

    默认,loadCSS把stylesheet插入到页面所有的CSS和JS资源后面,使用before精确插入点

    1
    2
    3
    4
    5
    6
    7
    8
    <head>
    ...
    <script id="loadcss">
    // load a CSS file just before the script element containing this code
    loadCSS( "path/to/mystylesheet.css", document.getElementById("loadcss") );
    </script>
    ...
    </head>
  • *media * 默认值是all

  • attributes

    1
    2
    3
    4
    5
    6
    7
    8
    9
    loadCSS( 
    "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css",
    null,
    null,
    {
    "crossorigin": "anonymous",
    "integrity": "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
    }
    );
  • Using with onload

    1
    2
    3
    4
    var stylesheet = loadCSS( "path/to/mystylesheet.css" );
    onloadCSS( stylesheet, function() {
    console.log( "Stylesheet has loaded." );
    });
-------------要说再见啦感谢大佬的光临~-------------