简体   繁体   English

如何知道动态加载的CSS文件何时完全加载并处于活动状态?

[英]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). 我使用了StackOverflow的帖子中描述的技术,将CSS文件动态添加到HTML页面的HEAD标签(在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. 作者将检查CSS文件是否已完全加载的方法描述为“丑陋”(我认为是;-); 另一篇文章建议使用“惰性加载器”(请参见已接受)。该帖子中的答案),其中考虑了跨浏览器的问题。 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? 我的问题是:我上次提到该帖子(以及浏览器技术的许多改进)已经一年多了,有没有一种可靠的,跨浏览器的方法来检查动态加载的CSS文件是否已准备好使用?

You can achieve it by loading your CSS file with an img . 您可以通过使用img加载CSS文件来实现。

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/ 此处的更多信息: 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');

}());​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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