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.
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);
3 Comments
Michael Mior
 Note that IE isn't always happy about 
  link tags being inserted this way. Check for document.createStylesheet and use if it eists.Howdy_McGee
 honestly I don't care too much for IE so not a problem. Thanks Ben!
  Huy Nguyen
 Use 
  document.head.appendChild(element); instead of document.getElementsByTagName("head")[0].appendChild(element);Alternative one liner:
document.head.insertAdjacentHTML( 'beforeend', '<link rel=stylesheet href=/ext.css>' );
1 Comment
waldyrious
 Nice! This is the neatest solution I've found so far :)
  
linknode to the DOM same as you would add apordivnode to the document. Have you tried that? The question is whether the style would be applied. I really don't know.... Good question. Someone tried it here: stackoverflow.com/questions/512070/…