延迟未使用的CSS [英] Defer unused CSS

查看:131
本文介绍了延迟未使用的CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关键的CSS流程,可以防止页面的首屏内容出现未样式化内容(FOUC).

我被Google PageSpeed见解(灯塔)和/或Chrome的性能审核突出显示了推迟未使用的CSS"这一点.

我看过其他文章,但它们无效.

总结一下,到目前为止我已经尝试过了.

  • loadCSS()
  • 使用requestAnimationFrame的脚本

参考: CSS投放优化:如何推迟CSS加载? /a>

如果我延迟通过setTimeout加载脚本的固定时间为3秒,那么推迟未使用的CSS"问题就消失了. Google PageSpeed Insights测试(移动设备)需要3秒,因为它们是较慢的设备,而台式机通常需要3秒,而台式机通常具有更大的处理能力(请注意,并非总是如此,因此不包括基于用户代理的逻辑).

因此,问题归结为如何不考虑设备类型或规格,如何以最少的时间延迟加载CSS.

请随意提出任何粗略的想法,我会尝试一下并提出报告,如果您的想法可行,我们将更新代码并标记您的答案已选定.

列表上的下一个要尝试的是requestAnimationFrame +较小的固定延迟.

解决方案

基于两个触发器(以先发生者为准)手动加载CSS.

  • [setTimeout为2500ms]
  • [滚动事件]

<script>
    var raf = requestAnimationFrame || mozRequestAnimationFrame ||
    webkitRequestAnimationFrame || msRequestAnimationFrame;
    var app_css_loaded = false;
    /* console.log(performance.now() + ' - ' + '1. async css script init'); */
    var loadAppCss = function(){
        if(!app_css_loaded) {
            app_css_loaded = true;
            var l = document.createElement('link'); l.rel = 'stylesheet';
            l.href = 'YOUR_COMBINED_AND_MINIFIED_CSS_HERE.css';
            var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
            /* console.log(performance.now() + ' - ' + '5. script injected'); */
        }
    };
    var cb = function() {
        /* console.log(performance.now() + ' - ' + '3. cb called'); */
        setTimeout(function(){
            /* console.log(performance.now() + ' - ' + '4. timeout start'); */
            loadAppCss();
            /* console.log(performance.now() + ' - ' + '6. timeout end'); */
        }, 3000);
    };

    window.addEventListener('load', function(){
        /* console.log(performance.now() + ' - ' + '2. triggering cb directly'); */
        if(raf) { raf(cb); } else { cb(); };
    });
    var loadAppCssOnScroll = function(){
        /* console.log(performance.now() + ' - ' + '### triggering cb on scroll'); */
        window.removeEventListener('scroll', loadAppCssOnScroll);
        if(raf) { raf(loadAppCss); } else { loadAppCss() };
    };
    window.addEventListener('scroll', loadAppCssOnScroll);
</script>

这使有关推迟未使用CSS的PageSpeed洞察力建议消失了.

如果大多数浏览器中的选项卡已在后台打开,则

requestAnimationFrame(如果有)将使CSS文件停止加载.如果不符合您的要求,则可以将其从上面的代码中删除. 参考

console.log()并非在所有浏览器中都可用.不要在生产中使用它. 参考

I have a critcal CSS process in place that prevents a flash-of-unstyled-content (FOUC) on above-the-fold content of a page.

I'm stuck on 'defer unused CSS' point that's being highlighted by Google PageSpeed insights (lighthouse) and/or Chrome's Performance Audit.

I've gone through other articles but they do not work.

To summarize I've tried so far.

  • loadCSS()
  • A script that uses requestAnimationFrame

Ref: CSS delivery optimization: How to defer css loading?

If I delay loading the script via setTimeout by a fixed time of 3 seconds the 'defer unused CSS' issue goes away. 3 seconds is what's needed for Google PageSpeed Insights test (mobile) as they are slower devices but 3 seconds is a lot for desktops which generally has more processing power (note, not always true, hence excluding user-agent based logic).

So the question boils down to how do I delay loading the CSS by the least amount of time irrespective of the device type or specs.

Feel free to throw any rough ideas, I'll try them out and report back, if your idea works, we'll update the code and mark your answer has the chosen one.

Next on my list to try is requestAnimationFrame + small fixed delay.

解决方案

Manually loading a CSS based on two triggers, whichever occurs first.

  • [setTimeout of 2500ms]
  • [Scroll event]

<script>
    var raf = requestAnimationFrame || mozRequestAnimationFrame ||
    webkitRequestAnimationFrame || msRequestAnimationFrame;
    var app_css_loaded = false;
    /* console.log(performance.now() + ' - ' + '1. async css script init'); */
    var loadAppCss = function(){
        if(!app_css_loaded) {
            app_css_loaded = true;
            var l = document.createElement('link'); l.rel = 'stylesheet';
            l.href = 'YOUR_COMBINED_AND_MINIFIED_CSS_HERE.css';
            var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
            /* console.log(performance.now() + ' - ' + '5. script injected'); */
        }
    };
    var cb = function() {
        /* console.log(performance.now() + ' - ' + '3. cb called'); */
        setTimeout(function(){
            /* console.log(performance.now() + ' - ' + '4. timeout start'); */
            loadAppCss();
            /* console.log(performance.now() + ' - ' + '6. timeout end'); */
        }, 3000);
    };

    window.addEventListener('load', function(){
        /* console.log(performance.now() + ' - ' + '2. triggering cb directly'); */
        if(raf) { raf(cb); } else { cb(); };
    });
    var loadAppCssOnScroll = function(){
        /* console.log(performance.now() + ' - ' + '### triggering cb on scroll'); */
        window.removeEventListener('scroll', loadAppCssOnScroll);
        if(raf) { raf(loadAppCss); } else { loadAppCss() };
    };
    window.addEventListener('scroll', loadAppCssOnScroll);
</script>

This makes the PageSpeed insights recommendation regarding defer unused CSS go away.

requestAnimationFrame, if available, will stall the CSS file from loading if the tab has opened in the background in most browsers. You could remove it from the above code if it does not meet your requirements. Ref

console.log() is not available in all browsers. Do not use it in production. Ref

这篇关于延迟未使用的CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆