samedi 5 mai 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:
$('h1').css("color","red");

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";            document.head.appendChild(datuURIs);        }addStyle('h1{color:pink;}');addStyle('h2{width:200px;}body{background:yellow}');

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.

Aucun commentaire:

Enregistrer un commentaire