1

I'm having an issue inserting a CSS @import rule into my <body> in Internet Explorer 8. I'm doing this as a way to defer non-critical CSS.

When I run the following code I get an "Unknown Runtime Error" on line 6 (ref_obj.innerHTML = ...):

var css_path_str = "my.css",
el_body = document.getElementsByTagName('body')[0],
ref_obj = document.createElement("style");

ref_obj.type = "text/css";
ref_obj.innerHTML = "@import url(\""+css_path_1_str+"\");";

el_body.appendChild(ref_obj);

As you can probably guess, the code works on Chrome and Firefox without any issue.

After doing a search here on SO, I stumbled on this post - Why is document.getElementById('tableId').innerHTML not working in IE8? - where it says that innerHTML for STYLE [and a few other elements] on IE is read-only.

Any ideas how I can edit my code to work around these limitations?

NOTE: Only pure Vanilla JavaScript.

EDIT:

Problem solved, but just for completeness, here is the code that should work (cross-browser).

var css_path_str = "my.css",
el_body = document.getElementsByTagName('body')[0],
ref_obj = document.createElement("style");
ref_obj.type = "text/css";

el_body.appendChild(ref_obj);

if(ref_obj.styleSheet)
{
    //IE
    ref_obj.styleSheet.cssText = "@import url(\""+css_path_str+"\");";
}
else
{
    //Other Browsers
    var ref_obj_text_node_obj = document.createTextNode("@import url(\""+css_path_str+"\");");
    ref_obj.appendChild(ref_obj_text_node_obj);
}
Community
  • 1
  • 1
ObiHill
  • 11,448
  • 20
  • 86
  • 135

1 Answers1

1

What you can do to make IE happy is use the styleSheet.cssText property of the node after you've inserted it into the DOM:

var css_path_str = "my.css",
el_body = document.getElementsByTagName('body')[0],
ref_obj = document.createElement("style");
ref_obj.type = "text/css";

el_body.appendChild(ref_obj);
ref_obj.styleSheet.cssText = "@import url(\""+css_path_str+"\");";
ObiHill
  • 11,448
  • 20
  • 86
  • 135
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Hmmm...it's saying "styleSheet is null or not an object". – ObiHill Jul 05 '15 at 14:43
  • Also, if I don't remove `ref_obj.type = "text/css";`, IE crashes. What a weird browser. – ObiHill Jul 05 '15 at 14:46
  • @ObinwanneHill that's odd, but the `type` attribute isn't needed anyway; browsers always interpret ` – Pointy Jul 05 '15 at 14:48
  • You are quite right. Apparently, I have to append the ` – ObiHill Jul 05 '15 at 15:04
  • 1
    Edited your answer inline with my original snippet. I hope you don't mind? – ObiHill Jul 05 '15 at 15:11