Welcome to WebmasterWorld Guest from 54.167.40.25

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)

New User

10+ Year Member

joined:Apr 18, 2003
posts:2
votes: 0


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)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 10, 2001
posts:793
votes: 0


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)

Senior Member

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

joined:May 26, 2000
posts:37301
votes: 0


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)

New User

10+ Year Member

joined:Apr 18, 2003
posts:2
votes: 0


Thanks! That was really helpful.