简体   繁体   中英

How to know when a dynamically loaded CSS file is fully loaded and active?

I have used a technique described in a post on StackOverflow to dynamically add a CSS file to the HEAD tag of an HTML page (in JavaScript). The method to check whether the CSS file has been fully loaded (see the same post) is described by its author as 'ugly' and in my opinion it is ;-) Yet another post suggests using a 'lazy loader' (see the accepted answer in that post) that takes cross-browser issues into account. Though the code looks fine, is seems rather complex for the task at hand.

My question is: More than a year after the post that I have last mentioned (and a lot of improvements in browser techniques), is there a reliable, cross-browser way to check whether a dynamically loaded CSS file is ready to use?

You can achieve it by loading your CSS file with an img .

var img = document.createElement("img");

img.onerror = function()
{
    console.log("loaded");
}

img.src = url;

More information here: http://www.backalleycoder.com/2011/03/20/link-tag-css-stylesheet-load-event/

try something like this

(function() {
    function cssLoader(url) {
        var link = document.createElement("link");
        link.onload = function(){
            console.log('loaded');
        };
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("type", "text/css");
        link.setAttribute("href", url);
        document.getElementsByTagName("head")[0].appendChild(link)
    }

    cssLoader('http://jsfiddle.net/css/style.css');

}());​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM