如何知道动态加载的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). 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.

我已经使用StackOverflow上的帖子中描述的技术将CSS文件动态添加到HTML页面的HEAD标记中(在JavaScript中)。检查CSS文件是否已完全加载的方法(参见同一篇文章)被其作者描述为“丑陋”,在我看来是;-)另一篇文章建议使用“懒惰加载器”(参见接受)该帖子中的答案)将跨浏览器问题考虑在内。虽然代码看起来很好,但对于手头的任务来说似乎相当复杂。

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文件是否可以使用?

2 个解决方案

#1


0  

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');

}());​

#2


0  

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/


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/03/29/3315406138c2ef417a0f6338e0bac913.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com