When is a stylesheet added to document.styleSheets

后端 未结 2 1345
暖寄归人
暖寄归人 2021-02-20 02:17

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 t

相关标签:
2条回答
  • 2021-02-20 02:36

    This should help: 'When is a stylesheet really loaded'

    As for 'Example 2'. It will break if there is stylesheet loading when you call addStylesheetRules(), of course that is in Chrome.

    0 讨论(0)
  • 2021-02-20 02:41

    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.

    0 讨论(0)
提交回复
热议问题