Last Updated: February 25, 2016
·
714
· chetan_raj

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');
}

1 Response
Add your response

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 ·