Tuesday, December 23, 2008

Dynamically Adding Styles via Link using JavaScript

So you want to add CSS styles using a URL to a stylesheet? That's different than adding inline styles. Luckily, it's pretty straightforward except for IE's party foul which prevents adding styles the standard way (it has to do everything its own special way).

Answer brought to you by Mark McLaren:
http://cse-mjmcl.cse.bris.ac.uk/blog/2005/08/18/1124396539593.html

Here is the code should his blog disappear from the internet:

if(document.createStyleSheet) {
document.createStyleSheet('http://server/stylesheet.css');
} else {
var styles = "@import url(' http://server/stylesheet.css ');";
var newSS=document.createElement('link');
newSS.rel='stylesheet';
newSS.href='data:text/css,'+escape(styles);
document.getElementsByTagName("head")[0].appendChild(newSS);
}

No comments:

Labels

Blog Archive

Contributors