问题
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.
回答1:
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);
回答2:
Alternative one liner:
document.head.insertAdjacentHTML( 'beforeend', '<link rel=stylesheet href=/ext.css>' );
来源:https://stackoverflow.com/questions/7266069/adding-external-stylesheet-using-javascript