Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defer render blocking CSS bundles in ASP.NET MVC

When I use Google Page Speed Insights

it says that my CSS is render-blocking and hence slowing down the initial loading of the page. In previous projects I have added CSS dynamically with Javascript and this worked well to defer the loading. So what is the best way to prevent render-blocking while still using bundles?

In bundle.config I have:

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"
                  ));

In _Layout.cshtml

@Styles.Render("~/Content/css")
like image 320
Stack Man Avatar asked Sep 01 '25 10:09

Stack Man


1 Answers

I found a solution myself by using the following HTML:

<script type="text/javascript">

    function load_css_async(filename) {


        var cb = function () {
            var l = document.createElement('link'); l.rel = 'stylesheet';
            l.href = filename;
            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>


@Styles.RenderFormat("<script type=\"text/javascript\">load_css_async('{0}')</script>", "~/Content/css")

And that has given me 100 / 100 in Page Insights :)

like image 173
Stack Man Avatar answered Sep 03 '25 00:09

Stack Man