Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6791637
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T17:52:15+00:00 2026-05-26T17:52:15+00:00

I’m trying to dynamically add a css stylesheet rule using javascript, something like example

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T17:52:15+00:00Added an answer on May 26, 2026 at 5:52 pm

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I used javascript for loading a picture on my website depending on which small
I've got a string that has curly quotes in it. I'd like to replace
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.