Posted on 31/05/2012. By Pete Otaqui.
Since I actually checked the search queries leading to this site, I found that quite a few people come here looking to learn about loading CSS with Javascript. I posted about getting an onload callback when loading css, but I thought I’d also post a really simple method for loading CSS without any dependencies.
The loadcss() function below is very straightforward – it just creates a link tag with the appropriate attributes and appends it to the head of the document.
You can see a demo of the loadcss script in action .
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Load CSS With Javascript</title> </head> <body> <h1>Load CSS With Javascript</h1> <button>Load the CSS</button> <script type="text/javascript" src="loadcss.js"></script> <script type="text/javascript"> /** * Loads a CSS file from the supplied URL * @param {String} url The URL of the CSS file, if its relative it will be to the current page's url * @return {HTMLElement} The <link> which was appended to the <head> */ function loadcss(url) { var head = document.getElementsByTagName('head')[0], link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = url; head.appendChild(link); return link; } // I've used raw DOM API here, but it would be even simpler // with something like jQuery var button = document.getElementsByTagName('button')[0]; button.addEventListener('click', function(ev) { loadcss('my_css_file.css'); }, false); </script> </body> </html>