Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding External Stylesheet using JavaScript

I need to add an link to an external css file in my header using an external javascript file. Don't ask why; I just need to do it. document.write() doesn't work btw.

like image 568
Howdy_McGee Avatar asked Sep 01 '11 04:09

Howdy_McGee


2 Answers

var element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", "external.css");
document.getElementsByTagName("head")[0].appendChild(element);
like image 79
Ben Avatar answered Oct 08 '22 06:10

Ben


Alternative one liner:

document.head.insertAdjacentHTML( 'beforeend', '<link rel=stylesheet href=/ext.css>' );
like image 29
Adria Avatar answered Oct 08 '22 04:10

Adria