Apr 29, 2014

Javascript load CSS

Javascript load CSS

To load a CSS file using Javascript, use the following code:

var cssUrl = "/styles/common.css";

$(document.head).append(
$("<link/>")
.attr({
rel: "stylesheet",
type: "text/css",
href: cssUrl
})
);


The preceding code uses jQuery. To do the same thing without jQuery, use the following code:

var cssUrl = "/styles/common.css";

var head = document.getElementsByTagName("head")[0];

var link = document.createElement("link");

link.rel = "stylesheet";
link.type = "text/css";
link.href = cssUrl;

document.head.appendChild(link);


Note that this loading technique is asynchronous.

 

SOURCE

No comments: