How to use Javascript to check and load CSS if not loaded?

Just check to see if a <link> element exists with the href attribute set to your CSS file’s URL:

if (!$("link[href="https://stackoverflow.com/path/to.css"]").length)
    $('<link href="https://stackoverflow.com/path/to.css" rel="stylesheet">').appendTo("head");

The plain ol’ JS method is simple too, using the document.styleSheets collection:

function loadCSSIfNotAlreadyLoadedForSomeReason () {
    var ss = document.styleSheets;
    for (var i = 0, max = ss.length; i < max; i++) {
        if (ss[i].href == "https://stackoverflow.com/path/to.css")
            return;
    }
    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = "https://stackoverflow.com/path/to.css";

    document.getElementsByTagName("head")[0].appendChild(link);
}
loadCSSIfNotAlreadyLoadedForSomeReason();

Leave a Comment