如何使用Google Page Speed CSS加载脚本推迟多个CSS文件

时间:2015-03-14 14:14:27

标签: javascript

我使用Google Page Speed CSS加载脚本来推迟更大的css文件。

<script async>
    var cb = function() {
        var l = document.createElement('link');
        l.rel = 'stylesheet';
        l.href = '<?php echo $root; ?>css/custom.css';
        var h = document.getElementsByTagName('head')[0];
        h.parentNode.insertBefore(l, h);
    };
    var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
    if (raf) raf(cb);
    else window.addEventListener('load', cb);
</script>

我如何推迟这些脚本?

<link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

1 个答案:

答案 0 :(得分:1)

扩展代码示例:

var loadCSSFiles = function() {
    var links = ["//example.com/css/custom.css", "//fonts.googleapis.com/css?family=PT+Sans", "//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"],
        headElement = document.getElementsByTagName("head")[0],
        linkElement, i;
    for (i = 0; i < links.length; i++) {
        linkElement = document.createElement("link");
        linkElement.rel = "stylesheet";
        linkElement.href = links[i];
        headElement.appendChild(linkElement);
    }
};
var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) {
    raf(loadCSSFiles);
} else {
    window.addEventListener("load", loadCSSFiles);
}

注意:我将insertBefore更改为appendChild,前者似乎不正确,因为它会将样式表放在文档头之外。