My goal was to keep all my styles in a style sheet and out of my xhtml. It turns out that I did not need to add a style sheet dynamically to accomplish this.
Here's my solution.
First, I created a div only the IE hack requires. I hid it from all but IE browsers using IE's proprietary conditional statements:
Code:
<!--[if IE]>
<div id="ie-hack">
<![endif]-->
and
<!--[if IE]>
</div>
<![endif]-->
Then I created an external stylesheet visible to all browsers in my document's head and hid the JavaScript I want visible only to IE browsers in my document's body. The JavaScript adds classes to three divisions (including the division visible only to IE browsers) if my visitor's window is open or is resized to less than 700px:
Code:
<head>
<link rel="stylesheet" href="layout.css" type="text/css" />
</head>
<body>
<!--[if IE]>
<script type="text/JavaScript">
var minlimit = 700 // The value (in pixels) below which the new stylesheet kicks in.
window.onload = minWidth;
window.onresize = minWidth;
function minWidth() {
if(document.getElementById) {
if(document.body.offsetWidth <= minlimit)
{
document.getElementById('ie-hack').className='ie-hack-fixed';
document.getElementById('header').className='header-fixed';
document.getElementById('footer').className='footer-fixed';
}}
else return false;
}
//
</script>
<![endif]-->
Finally, the layout visible to every browser includes styles for the three classes that exist only for IE browsers IF the visitor's window is open to less than or equal to 700px. All but IE browsers ignore them because as far as they know, the classes don't exist!
This solution works well and validates.
I got the idea for the JavaScript from Christian Jacobsson's "Change CSS with JavaScript" and "Hide CSS from browsers." Visit http://hem.fyristorg.com/g-force/test/ to see Christian's HTML and CSS experiments.
I did find what I thought would be a direct answer my question (how to add a link to a style sheet dynamically?) but for some reason it isn't working.
Can anyone tell why not? The methods I attempt to use are described at http://developer.apple.com/internet/...pt/dom2i.html# :
Code:
<head>
<link rel="stylesheet" id="primary-stylesheet" type="text/css" href="layout.css" />
</head>
<body>
<!--[if IE]>
<script type="text/JavaScript">
var minlimit = 700 // The value (in pixels) below which the new stylesheet kicks in.
window.onload = minWidth;
window.onresize = minWidth;
function minWidth() {
if(document.body.offsetWidth <= minlimit)
{
function insertLINK(){
var newLINK = document.createElement("link");
var newText = document.createTextNode(' rel="stylesheet" type="text/css" title="ie hack" href="ie-no-min-width-hack.css" ');
newLINK.appendChild(newText);
var headElm = document.getElementById("primary-stylesheet");
var refLINK = headElm.getElementsByTagName("link").item(2);
headElm.insertBefore(newLINK,refLINK);
}
}
else return false;
}
//
</script>
<![endif]-->
-- Chris