4

I am dynamically creating a large stylesheet as a string and desiring to injecting it into an iframe. Initially I approached it like this:

var css = '.newstyle { margin: 20px; } .newstyle2 { margin: 20px; }';
$('iframe').contents().find('head').append('<style type="text/css">'+css+'</style>');

Unfortunately, IE7 does not like this method. I'm not sure how else to approach this injection. Is there a cross-browser solution that will enable me to inject a mass of CSS from a string?

stillmotion
  • 4,608
  • 4
  • 30
  • 36
  • Try the non-jQuery solution here: http://stackoverflow.com/questions/3158370/injected-link-stylesheet-takes-precedence-over-existing-styles-in-ie7 – Matt Ball Nov 01 '11 at 03:52
  • I am looking to not use the tag to reduce the amount of http requests. Speed is key in this script. – stillmotion Nov 01 '11 at 04:22
  • Try injecting the css into the body... I seem to remember IE being fussy about that. – Mottie Nov 01 '11 at 04:55

1 Answers1

2

You could use document.stylesheets for this purpose. It gives you access to the style sheets within a page.

Check this article: http://kentbrewster.com/creating-dynamic-stylesheets/ — It's a bit older and not jQuery–centric, but I'm sure you can adjust it to your needs. I've used this technique a few years back and I believe it worked fine in all browsers after tweaking a bit.

Here's a bit more information on the stylesheets property:

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
polarblau
  • 17,649
  • 7
  • 63
  • 84