Want to load up CSS files using Javascript? Here’s the “old school” way of doing it, which hopefully works across all browsers. In theory, you would use setAttribute
unfortunately IE6 doesn’t support it consistently.
1 2 3 4 5 6 7 8 9 10 11 12 | var cssId = 'myCss'; // you could encode the css path itself to generate id.. if (!document.getElementById(cssId)) { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.id = cssId; link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'http://website.com/css/stylesheet.css'; link.media = 'all'; head.appendChild(link); } |
VanillaJS
Here is an example that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:
1 2 3 4 5 6 7 8 9 10 11 | <script type="text/javascript"> var file = location.pathname.split( "/" ).pop(); var link = document.createElement( "link" ); link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css"; link.type = "text/css"; link.rel = "stylesheet"; link.media = "screen,print"; document.getElementsByTagName( "head" )[0].appendChild( link ); </script> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.