Jan. 20, 2012

Add inline CSS or remote CSS file with JavaScript

In case you don't have access to HTML and can't either insert inline CSS  or inject remote CSS files, JavaScript can help.  Here are two sloppy functions that will let you do this. To use:

css_add_inline( " * { color: crimson !important } " );

or

css_add_file( "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/redmond/jquery.ui.all.css" );

<script type="text/javascript">

function css_add_file( css_url ) {
	var c = document.createElement('link');
	c.type = 'text/css';
	c.rel = 'stylesheet';
	c.href = css_url;
	c.media = 'screen';
	c.title = 'dynamicLoadedSheet';
	document.getElementsByTagName("head")[0].appendChild(c);
}

function css_add_inline( css_code ) {
	var div = document.createElement( "div" );
	div.innerHTML = "<p>x</p><style>" + css_code + "</style>";
	document.body.appendChild(div.childNodes[1]);
}

</script>

Live example:


 

(Edit: when I was typing this up, I left out the 'x' character in the p tag, which is required for this to work in IE.  If you run into any browsers that this doesn't work in, leave a comment below.)

 

Find this interesting, or useful? Consider sharing the post.

Leave a Reply

Your email address will not be published. Required fields are marked *

Posts on this blog solely represent my personal opinions and technical experience.

© 2009-2017 Edin (Dino) Beslagic