Freelance Web Developer

Say Hi

Apr 4, 2012

Adding Dynamic CSS style rules with Data URIs and JavaScript

Whats the Data URIs?

Data URI scheme provides a way to resources to be fetched in a single HTTP request. which is more efficient

The format

data:[mime type=""][;charset=charset][;base64],encoded data=""

The Why?

It saves HTTP Requests, and make webpages load faster.

Adding Dynamic Style

How we do it with jQuery:

How we do it with palin JavaScript:
document.getElementById("hello").style.color = "#000267";

And using DataURIs.

function addStyle(css){
            var datuURIs = document.createElement("link");
            document.head = document.head || document.getElementsByTagName('head'[0]);
            datuURIs.href = "data:text/css,"+css;
            datuURIs.rel = "stylesheet";



I think doing it using DataURI is easy, because it looks same like CSS code. You just have to use one JS function and can add style rules anywhere in the JS code, whenever you want one the fly.

Try the code here.

Feel free to share your thought about it. I am on twitter as @motyar.

Labels: , ,

By :