jQuery plugin loadStylesheet with callback

by mjaric

HTML

<div>
    <p class="ui-icon">some text</p>
</div>

CSS

/* something which should be included in css file which should be loaded in page
 * Use content in $('body').loadStylesheet() as second parameter, this will distingush this css file from other insluded */
.stylesheet {
    content: "/path/to/stylesheets/file.css";
}

p {
    margin: 10px;
    border-radius: 5px;
    background:#def;
    padding: 10px;
    border: 1px solid #acf;
}

JavaScript

$.fn.loadStylesheet = function(url, content, callback) {
    var link = $("<link type='text/css' rel='stylesheet' href='" + url + "' />");

    function checkIfLoaded(url, content, callback) {
        var stylesheetName = $('input[value="' + url + '"].stylesheet').css("content");
        if (stylesheetName == "'" + content + "'" || stylesheetName == content) {
            callback(url);
            return true;
        }
        return false;
    }

    function waitTillLoaded(url, content, callback) {
        if (checkIfLoaded(url, content, callback)) {
            return;
        }
        setTimeout((function(u, c, f) {
            return function() {
                waitTillLoaded(u, c, f);
            };
        })(url, content, callback), 100);
    }

    if (checkIfLoaded(url, content, callback)) {
        return $(this);
    }
    waitTillLoaded(url, content, callback);

    if ($('input[value="' + url + '"].stylesheet').length < 1) {
        $(this).append($("<input type='hidden' class='stylesheet' value=" + url + " />"));
    }
    return $(this);
};
$('body').loadStylesheet("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css", "/path/to/stylesheets/file.css", function(url) {
    $('body>div').append("<p><b>Stylesheet:</b> <br/>" + url + "<br /><b>Status</b>: LOADED</p>");
});
$('body').loadStylesheet("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css", "/path/to/stylesheets/file.css", function(url) {
    $('body>div').append("<p><b>Stylesheet:</b> <br/>" + url + "<br /><b>Status</b>: LOADED</p>");
});