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")
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With