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.

Community
  • 1
  • 1
Max
  • 12,794
  • 30
  • 90
  • 142

2 Answers2

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Indeed it works. However I thought `DOM` modifications (i.e. when using methods such as `append`, `prepend` and the likes) where synchronous? – Max Aug 19 '12 at 15:33
  • 1
    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 `` tag to the document. – Pointy Aug 19 '12 at 15:47
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?

Community
  • 1
  • 1
Mitchell Lee
  • 456
  • 3
  • 14