Load an external stylesheet using JavaScript

· 7 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.


removeCss() gets passed an Id parameter:



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;

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

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

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

Great books are available on JavaScript and jQuery.

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

7 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!

  6. mobile says:

    You would with this solution have more css files initially loaded but you have a more dynamic way of switching css layouts.

  7. Aida says:

    I’d like to share one more way to load not only css but all the assets (js, css, images) and handle onload event for the bunch of files. It’s Not the answer you re looking for? Browse other questions tagged javascript html css dhtml or ask your own question .

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="">