Defer unused CSS

感情迁移 提交于 2019-12-07 22:41:19

Keep in mind that Lighthouse is an advisory tool; it gives recommendations, not requirements. It's up to you to decide if those recommendations make sense in the context of your business requirements. These include weighing the time and effort determining and implementing a solution against the impact of the issue.

Google has advice on resolving Lighthouse's "defer unused CSS" recommendations: Defer unused CSS. To summarize: CSS required immediately by the page should be inlined rather than loaded from a separate file.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!