Last Updated: February 25, 2016
·
919
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside