Load CSS whenever required
Javascript
function loadCSS(url) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
jQuery
function loadCSS(url) {
$("<link>", {
rel: 'stylesheet',
type: 'text/css',
href: url
}).appendTo('head');
}
Written by Chetan
Related protips
1 Response
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/46110/15927fc52919e9223adc7ed99e125d4d.jpeg)
This is great for 3rd party scripts (e.g. a bookmarklet). However, if you use this for a web application, it will turn into a nightmare.
Imagine testing a page and everything looks good. Then, going to another page, returning the original, and everything is misaligned.
It is not an unlikely scenario that dynamically loaded page-specific CSS will accidentally collided with other CSS.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Css
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#