Script-injected CSS will no longer block rendering in Chrome

Last week, we heard about a small but potentially important bug fix in Chrome (thanks to @smashingmag for Tweeting about it):

Tweet from @smashingmag about Chrome update

As you probably already know, browsers wait for CSS to load before starting to render a page. This is true for CSS referenced directly in the HTML, but what if a reference to a style sheet is added dynamically by JavaScript?

Currently, browser behaviour is variable. Internet Explorer and Firefox don’t wait for the style sheet before displaying content. Instead, they render the page using default styles, then make any necessary changes after the style sheet has loaded.

Chrome, however, waits for the style sheet to load before rendering anything. This avoids a flash of unstyled (or incorrectly styled) content. But it can also add significantly to the time it takes for the web page to start displaying if either the JavaScript or the CSS file takes a while to load. This is most likely to crop up in the context of third-party content, such as an embedded sign-up form for a newsletter: a relatively minor element suddenly becomes a single point of failure that could prevent the whole page displaying.

The issue was illustrated with a simple test case (taken from https://code.google.com/p/chromium/issues/detail?id=571725):

<script>
  var link = document.createElement('link');
  link.setAttribute('rel', 'stylesheet');
  link.setAttribute('type', 'text/css');
  // This CSS returns "div { color: red; }" with a 10 seconds delay
  link.setAttribute('href', 'really-really-slow.css');
  document.head.appendChild(link);
</script>
<div>This should be black then red.</div>

Internet Explorer and Firefox display the text immediately, in black to start with, then change it to red once the style sheet has loaded. Chrome doesn’t display the text at all until the style sheet has loaded, at which point it appears in red. We recreated the test in Performance Analyser, and the filmstrip below illustrates the point:

 Filmstrip from Performance Analyser

The update will bring Chrome into line with Firefox and Internet Explorer.

Practically speaking, this might not actually make a huge difference. CSS added in this way will often be injected by an externally hosted JavaScript file. As long as that file is loaded asynchronously, Chrome will start displaying the page without waiting for the CSS to load. Still, the fix will at least reduce the risk of script-injected CSS delaying the point at which a web page is displayed.

Published date:  04 February 2016

Written by:  Alex Painter

comments powered by Disqus

Filter By Service

Filter By Date