Adding External Stylesheet using JavaScript

久未见 提交于 2021-02-07 06:41:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!