Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can CSS file loading be deferred via http LINK header and does that block rendering

If we use the http link header to provide a link to a CSS file very early on what browsers would NOT download this link and are there any browsers for which a CSS file provided this way would block rendering the "above the fold content"?

This would be the HTTP header:

Link: <style.css>; rel="stylesheet"

This an untested PHP implementation of the same thing (if one does not configure apache to do it like hinted at in the link above):

<?php
header('Link: <style.css>; rel="stylesheet"');
?>

Question: cross browser compatibility and render blocking behavior

like image 782
C.O. Avatar asked Nov 29 '15 19:11

C.O.


1 Answers

Apologies in advance that my response is not directly in reference to use of the http Link header. If the objective is to try and load non-critical CSS asynchronously(in the background without blocking page rendering), this can be achieved with JavaScript. See the loadCSS project for some good documentation and examples.

Normally, all CSS files included in a standard way(e.g. <link href="path/to/mystylesheet.css" rel="stylesheet">) do in fact block page rendering until ALL stylesheets have finished loading. This is for good performance reasons by browsers in order to prevent multiple re-layouts and re-paints when loading a page after each stylesheet finishes loading.

The idea with this solution is basically to alter the media type for the non-critical stylesheet(s) to something the browser will see as unimportant for page rendering(e.g. "only x"), and then manually switch the media type back to the standard "all" (or other value as needed), which is likely after then resource is finished loading, but could be further deferred if desired based on your use case.

This method is pretty reliable as long as you only need to to support relatively modern browsers. I've used it in production for content thats had millions of pageviews. You may be able to implement something similar using the Link header but you'd still need some client side script in place to detect when the resource finished loading and to switch the media type back to "all".

like image 167
munsellj Avatar answered Nov 18 '22 04:11

munsellj