tags:

views:

1023

answers:

4

Hello,

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

A: 

Hi

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

+1  A: 

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;
Alagu
Interresting, you code work only on firefox.
belaz
I haven't tested this out, you mean to say this doesn't work in internet Explorer?
Alagu
Yes.It doesnt work.
belaz
Ah. Thats bad, I shouldn't have got a vote for my answer.
Alagu
It works for Firefox, this is still a good answer.
belaz
A: 

What's the use case? I've done something similar based on the resolution of the site, so I might be able to help. But, I'd like to know why you're adding a stylesheet dynamically.

User-controlled themes?

Srdjan Pejic
I have a lot of pages to modify, to include a tooltip on a form.Theses pages aren't built the same manner ( some are 8 years old, most haven't the same templates and design ).The purpose is to centralise all modifications in one JS included, to let others maintain code easier. That's the case.
belaz
Right. What I wanted to propose was to insert the tag, but then disable it and re-enable it when needed. That's obviously not gonna work here. Are you able to narrow down which line actually crashes the browser? Does it happen when you try to append the element?
Srdjan Pejic
Im not at the office now, i will check with colleagues later, on the other codes who interfere. Thank you for your concern but i think more and more that bug is specific to my configuration or crash because others scripts (a big medley i can't post).
belaz
That's cool and no problem. Hope I can help (somewhat) again. :)
Srdjan Pejic
A: 

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

belaz