Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a stylesheet added to document.styleSheets

I'm trying to dynamically add a css stylesheet rule using javascript, something like example 2 here.

It works most of the time, but there seems to be a race condition that makes it fail sometimes in (at least) Chrome (15.0.874 and 17.0.933). It happens infrequently when the cache is empty (or has been cleared).

Here's what I've been able to narrow it down to. First I load an external stylesheet by appending it to <head> and then I create a new stylesheet (where I would add rules). I then print the length of document.styleSheets (immediately and after 1 second).

$(function() {
    // it doesn't happen if this line is missing.
    $("head").append('<link rel="stylesheet" type="text/css"'+
                     'href="/css/normalize.css" />');

    var stylesheet = document.createElement("style");
    stylesheet.setAttribute("type", "text/css");
    document.getElementsByTagName('head')[0].appendChild(stylesheet);

    var b = $('body');
    b.append(document.styleSheets.length).append('<br/>');
    setTimeout(function() {
        b.append(document.styleSheets.length).append('<br/>');
    }, 1000);
});

(play with it at http://jsfiddle.net/amirshim/gAYzY/13/)

When the cache is clear, it sometimes prints 2 then 4 (jsfiddle adds it's own 2 css files), meaning it doesn't add either of the style sheets to document.styleSheets immediately... but probably waits for the external file to load.

Is this expected?

If so, is Example 2 on MDN (and many others out there) broken? Since line 27:

var s = document.styleSheets[document.styleSheets.length - 1];

might evaluate with document.styleSheets.length == 0

Note that this doesn't happen when I don't load the external CSS file first.

like image 545
Amir Avatar asked Nov 09 '11 04:11

Amir


Video Answer


1 Answers

If JavaScript is in the page below the CSS (which it almost always is) the HTML parser must wait with JS execution until the JS and CSS is fully loaded and parsed because of the fact that JS might request styling information (Chrome only does so when the script actually does this though). This effectively makes the loading of external CSS blocking in almost all cases. When you insert them later via JavaScript or there are no JS' in the page (or the JS is loaded non-blocking) CSS loads asynchronously meaning they're loaded and parsed without blocking the parsing of the DOM. Therefor the documents.stylesheets count only gets updated after the sheet is inside the DOM and that only happens after it is fully loaded and parsed.

In this situation there might be some timing differences involved. Considering most browsers only have a limited number of pipes through which they load data (some have only two like IE6, most have 6 and some even have 12 like IE9) the loading of the stylesheet is added at the end of the queue to be loaded. The browser is still loading things because you call you function on DOMReady. Which results in the stylesheet not being fully loaded and parsed one second later, so not affecting the document.stylesheets.length.

And all stylesheet examples i've run into on the web assume the dom is fully parsed and loaded. OffDOM stylesheets don't even allow rules to be inserted or checked due to the fact that they can have @import rules and those have to be loaded externally, so for browsers it's pretty hard to determine when its safe to interact with the sheet unless they're fully loaded and parsed. OffDOM stylesheets do expose an empty sheet property but won't let you interact with it until the sheet has been added to the DOM.

I've always found it better to insert a stylesheet dynamically and execute all changes in that one sheet and leaving the document.stylesheets alone. This has the great advantage that when you override styles with the same specificity you wont run into trouble because of insertion in the wrong sheet. Since document.stylesheets is a live nodeList, document.stylesheets[ 2 ] can point to another sheet every time you call the function (unless stored in a var). So I tend to use a dynamically inserted sheet and only operate on that one.

like image 75
PM5544 Avatar answered Oct 26 '22 10:10

PM5544