Add a link stylesheet dynamically in the <head&

2020-01-26 11:01发布

How to add a link stylesheet reference to the head of a document ?

I've found this code but it's not working with all browsers, it crashes my IE7 :

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(ss);

Thanks

3条回答
女痞
2楼-- · 2020-01-26 11:45

That was a simple cross reference javascript bug. Have a nice day.

查看更多
贼婆χ
3楼-- · 2020-01-26 11:48

Internet explorer will support innerHTML, though it adds reflow this would work:

var headHTML = document.getElementsByTagName('head')[0].innerHTML;
headHTML    += '<link type="text/css" rel="stylesheet" href="style.css">';
document.getElementsByTagName('head')[0].innerHTML = headHTML;
查看更多
该账号已被封号
4楼-- · 2020-01-26 11:49

In IE, you could try the createStyleSheet method? That takes URL as a parameter. I don't know whether there is an equivalent in FF/chrome though..

--Senthil

查看更多
登录 后发表回答