Dynamic CSS file loading
32
Gives you the ability to dynamically include a CSS file at any time in your HTML page using Javascript.
var CSS = {
load: /*static*/ function (url_, /*optional*/ media_) {
// We are preventing loading a file already loaded
var _links = document.getElementsByTagName("link");
if (_links.length > 0 && _links["href"] == url_) return;
// Optional parameters check
var _media = media_ === undefined || media_ === null ? "all" : media_;
var _elstyle = document.createElement("link");
_elstyle.setAttribute("rel", "stylesheet");
_elstyle.setAttribute("type", "text/css");
_elstyle.setAttribute("media", _media);
_elstyle.setAttribute("href", url_);
var _head = document.getElementsByTagName("head")[0];
_head.element.appendChild(_elstyle);
}
};





I went on to update the functionality to actually remove dynamically created links from the DOM when using a few stylesheets. I implemented this script on a site where you could choose between half a dozen stylesheets. I found that if you changed from stylesheet to stylesheet the head would grow with stylesheet as the current script only checks to see if the new stylesheet is the LAST one that has been loaded.
One thing to remember is that href works off absolute URI's, not relative!
Enjoy.
var CSS = {
load: /*static*/ function (url_, /*optional*/ media_)
{
// We are preventing loading a file already loaded
var _links = document.getElementsByTagName("link");
var _head = document.getElementsByTagName("head")[0];
// Loop through the length of the links
for( i = 0; _links.length > i; i++)
{
// If the href is already present, remove it
if (_links[i]["href"] == url_)
{
_head.removeChild(_links[i]);
}
}
// Optional parameters check
var _media = media_ === undefined || media_ === null ? "all" : media_;
// Build link element
var _elstyle = document.createElement("link");
_elstyle.setAttribute("rel", "stylesheet");
_elstyle.setAttribute("type", "text/css");
_elstyle.setAttribute("media", _media);
_elstyle.setAttribute("href", url_);
// Add style
_head.appendChild(_elstyle);
}
};
<script type="text/javascript">
CSS.load('http://example.com/path/to/file.css');
</script>