Welcome Message

"The difference between a successful person and others is not a lack of strength,
not a lack of knowledge, but rather a lack in will."
-Vince Lombardi

July 20, 2009

Dynamic Cascading Style Sheets using Javascript

The usefulness of being able to dynamically load a style sheet is fairly limited, but there is one very good reason to keep this tool handy: it lets you load a specific stylesheet for a specific browser. Instead of having one massive style sheet for every browser which visits your page, you can break out the stylesheets into browser specific Firefox, IE, Safari, Opera, etc styles which accommodate the eccentricities of each browser and let you serve smaller css files to your visitors to boot.

The code for this is just as simple as the javascript.

var headID = document.getElementsByTagName("head")[0];       
var cssNode = document.createElement('link');               
cssNode.type = 'text/css';                                  
cssNode.rel = 'stylesheet';                                 
cssNode.href = 'FireFox.css';                               
cssNode.media = 'screen';                                   

We get the <head> tag, then create the link and apply the attributes. When it's all set up we insert the new cssNode into the head section of our webpage where the various styles are instantly applied.

A complete reference for adding, creating, altering and deleting stylesheets and their elements can be found in a newer article titled Totally Pwn CSS with Javascript. If you are looking to do more than dynamically add a stylesheet you should definitely check out this article.


No comments:

Post a Comment

Thank you for your valuable comments.