【问题标题】:Detecting load of <link> resources?检测 <link> 资源的负载?
【发布时间】:2010-10-22 04:52:21
【问题描述】:

浏览器为&lt;script&gt;&lt;img&gt; 标签提供加载事件。有没有办法检测对元素的请求是否已经完成?

具体来说,我希望检测何时加载了 &lt;link&gt;'d 样式表。

不幸的是,我认为在我的情况下使用哨兵样式并检测来自computedStyle 的负载是不可行的。

【问题讨论】:

    标签: javascript css optimization


    【解决方案1】:

    可能有更简单的方法,但这对我有用。

    确保您的&lt;link&gt; 标签具有title 属性:

    <link title="myStyles" rel="stylesheet" href="style.css" />
    

    然后使用这样的函数来检查特定样式集中的样式是否存在:

    function linkLoaded(linkTitle, checkStyle)
    {
        for (var ix=0; ix<document.styleSheets.length; ix++) {
            try {
                if (document.styleSheets[ix].title == linkTitle) {
                    var mySheet=document.styleSheets[ix];
                    var myRules = mySheet.cssRules? mySheet.cssRules: mySheet.rules
                    for (var jx=0; jx<myRules.length; jx++) {
                        var thisSelector = myRules[jx].selectorText.toLowerCase();
                        if (thisSelector.substring(0, checkStyle.length) == checkStyle) {
                            alert("Found style!");
                            return;
                        }
                    }
                }
            }
            catch (err) {}    
        }
    
        alert("Not loaded!");
        return;
    }
    

    【讨论】:

    • 有时 .cssRules 和 .rules 会为空,所以添加一个 if (css.rules) 守卫是明智的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2019-04-24
    • 2010-10-29
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多