Load an external stylesheet using JavaScript

· 5 Comments · in CSS, JavaScript

There are times when you may not want to load a CSS file on page load, especially if it is a large file.

You can load that external file using only JavaScript.

Here’s how…

We will have two functions, loadCss() and removeCss().

loadCss() will append a CSS file using the <link> tag.
removeCss() removes it.

Parameter(s) are passed to the functions, enabling their usage for manipulating multiple files.

loadCss() gets passed a file and Id parameter. The Id is used to make the appended file unique and also enable us to remove it, if desired.

loadCss("/yourpath_to_css/dynamic.css","dynamic-css")

removeCss() gets passed an Id parameter:

removeCss("dynamic-css")

JavaScript

function loadCss(f,i){
	var _c = document.getElementById(i);
	//assures we don't add the same file again
	if( f !== "" && (typeof(_c) === 'undefined' || _c === null) ){
		var _e = document.createElement('link');
		_e.rel = "stylesheet";
		_e.type = "text/css";
		_e.href = f;
		_e.id = i;
		document.body.appendChild(_e);
	}
}

function removeCss(i){
	var _c = document.getElementById(i);
	if (typeof(_c) !== 'undefined' && _c !== null){
		document.body.removeChild(_c);
	}
}

Put it all together and you can see the working example here.

Tested in:
FF 3.6+, Safari, Chrome, IE8+
iOS

Great books are available on JavaScript and jQuery.

This entry was posted in CSS, JavaScript and tagged , .
Bookmark the permalink.

5 Responses to Load an external stylesheet using JavaScript

  1. googlepo says:

    There’s a wealth of information here. Thanks! I’ll be back for more.

  2. This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want…HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!

  3. Great article . Will definitely copy it to my website.

  4. It took me time to read all the tips, but I clearly loved the post. It proved to be very helpful to me and I’m certain to all of the commenters here!

  5. clarke ulmer says:

    Thanks to all for the kind comments!

Leave a Reply

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

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">