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);
}