11

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
  • You should be able to add a link node to the DOM same as you would add a p or div node 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/… Commented Sep 1, 2011 at 4:22
  • @Ray Toal - yup, the styles will be applied once you insert the link element on the head. Commented Sep 1, 2011 at 4:32

2 Answers 2

19
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);
Sign up to request clarification or add additional context in comments.

3 Comments

Note that IE isn't always happy about link tags being inserted this way. Check for document.createStylesheet and use if it eists.
honestly I don't care too much for IE so not a problem. Thanks Ben!
Use document.head.appendChild(element); instead of document.getElementsByTagName("head")[0].appendChild(element);
5

Alternative one liner:

document.head.insertAdjacentHTML( 'beforeend', '<link rel=stylesheet href=/ext.css>' );

1 Comment

Nice! This is the neatest solution I've found so far :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.