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
.
There’s a wealth of information here. Thanks! I’ll be back for more.
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!
Great article . Will definitely copy it to my website.
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!
Thanks to all for the kind comments!
You would with this solution have more css files initially loaded but you have a more dynamic way of switching css layouts.
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 .