2

I am loading a CSS stylesheet after page load with this code:

$("head").append($("<link>", {
    rel: "stylesheet",
    href: 'http://cdn.sstatic.net/stackoverflow/all.css',
    type: "text/css"
}));

Although this works fine (i.e. elements with classes from the newly added stylesheet are properly decorated), I am unable to query the CSS properties from that stylesheet using jQuery: I have created a jsFiddle to show the problem

How can I (ideally with jQuery) lookup the CSS properties of elements which classes correspond to CSS stylesheets added after page load?

PS: I am experiencing the issue with Firefox 14.0.1 but not with Chrome 21.0.1180.79.

2
  • The stylesheet won't load immediately. Commented Aug 19, 2012 at 15:25
  • 1
    You also cannot access the stylesheet rules programmatically since it's from different domain... in case you wanted to do that. Commented Aug 19, 2012 at 15:30

2 Answers 2

4

If you do your console.log() calls in a "load" handler, it works fine:

$("head").append($("<link>", {
    rel: "stylesheet",
    href: 'http://cdn.sstatic.net/stackoverflow/all.css',
    type: "text/css",
    load: function() {
      console.log($('#test1').css('color'));
      console.log($('#test2').css('color'));
      console.log($('#test3').css('color'));
      console.log($('#test4').css('color'));    
      }
  }));

Fiddle, updated.

Sign up to request clarification or add additional context in comments.

2 Comments

Indeed it works. However I thought DOM modifications (i.e. when using methods such as append, prepend and the likes) where synchronous?
The DOM is modified immediately, but an HTTP transaction must take place to fetch the stylesheet. (Even if it's cached, the browser may handle it asynchronously.) It's like adding an <img> tag to the document.
2

Likely the problem is due to the stylesheets not being fully loaded by the time you do your console.logs. Similar to dynamically rendering an image to the page with jquery, a stylesheet is a foriegn resource, and you need to account for the time it takes for the browser to pull down and apply the stylesheet before you can execute code that leverages.

A better approach to this problem (and a solution) can be found here: jQuery event that triggers after CSS is loaded?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.