HOW TO check if an external (cross-domain) CSS file is loaded using Javascript

css, javascript

Solution

This is actually what I did.

To ensure a specific CSS file is loaded, I added a style in the end of the CSS file. For example:

#ensure-cssload-8473649 {
  display: none
}

Now I have a JavaScript function which will fire the callback specified when the above style is loaded on the page:

var onCssLoad = function (options, callback) {
    var body = $("body");
    var div = document.createElement(constants.TAG_DIV);
    for (var key in options) {
        if (options.hasOwnProperty(key)) {
            if (key.toLowerCase() === "css") {
                continue;
            }
            div[key] = options[key];
        }
    }

    var css = options.css;
    if (css) {
        body.appendChild(div);
        var handle = -1;
        handle = window.setInterval(function () {
            var match = true;
            for (var key in css) {
                if (css.hasOwnProperty(key)) {
                    match = match && utils.getStyle(div, key) === css[key];
                }
            }

            if (match === true) {
                window.clearTimeout(handle);
                body.removeChild(div);
                callback();
            }
        }, 100);
    }
}

And this is how I used the function above:

onCssLoad({
    "id": "ensure-cssload-8473649",
    css: {
        display: "none"
    }
}, function () {
    // code when you want to execute 
    // after your CSS file is loaded
});

Here the 1st parameter takes the `options` where `id` is to check against the test style and css property to verify against what loaded from the CSS.

Problem

I have a function doing the following using `javascript`: - Create link element and set href=cssFile. - Insert the link element in head tag. - Create a div element. - Set the class name using setAttribute - `appendChild` the div on body. - Now getting CSS rule value using `document.defaultView.getComputedStyle(divElement, null)[cssRule]`. Now `getComputedStyle` is returning the default values, and if I wait on breakpoint using Firebug before `getComputedStyle` call, then it returns the CSS rule from the CSS injected. Regards, Munim

Original source