Welcome to WebmasterWorld Guest from 54.159.250.110

Forum Moderators: open

Message Too Old, No Replies

Dynamically load a css from js

js load css

   
9:03 am on Apr 18, 2003 (gmt 0)

10+ Year Member



I am new to js so this question may seam dumb and the answer obvious, but can anybody tell me how can I load dynamicaly a css from js.
9:41 am on Apr 18, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Using the DOM of course:

var oLink = document.createElement("link") 
oLink.href = "mypath/mycss.css";
oLink.rel = "stylesheet";
oLink.type = "text/css";
document.body.appendChild(oLink);

This will only work in DOM compatible browsers like Opera 7+, IE5+, and NN6+.

Josh

9:42 am on Apr 18, 2003 (gmt 0)

WebmasterWorld Senior Member tedster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



You can also use document.write() to add the appropriate text. Here's a simple script I've called from the <head> to give Netscape 4 it's own stylesheet, before I learned about the @import hack:

if (document.layers) {
document.write('<link rel=stylesheet href="nn4.css">')
}
else {
document.write('<link rel=stylesheet href="main.css">')
}
2:57 pm on Apr 18, 2003 (gmt 0)

10+ Year Member



Thanks! That was really helpful.