0

Add a stylesheet on the fly with javascript

Posted by Darren on Jan 20, 2010 in Coding, javascript

You may notice ive been dabbling in javascript more recently. As part of a project I need to insert a stylesheet through javascript, my first attempt lead to me being success; only in firefox. I decided to insert the stylesheet in the body of the HTML by updating the InnerHtml of a div i knew existed. This worked a treat in firefox but notta thing in other (probably right) browsers.

I set about doing it the right way and this is what I came with:
function add_stylesheet(){
if(document.createStyleSheet) {
document.createStyleSheet('http://counter.adcourier.com/share/css/share.css');
} else {
var styles = "@import url('http://counter.adcourier.com/share/css/share.css');";
var newSS=document.createElement('link');
newSS.rel='stylesheet';
newSS.href='data:text/css,'+escape(styles);
document.getElementsByTagName("head")[0].appendChild(newSS);
}
}

Cross browser and exactly what I wanted.

Tags: , , ,