【问题标题】:Dynamically loading stylesheets, cssRules is coming up as null [duplicate]动态加载样式表,cssRules 出现为 null [重复]
【发布时间】:2013-05-05 17:08:25
【问题描述】:

我正在尝试动态加载样式表,并使用 cssRules 属性检查它何时准备就绪,但它显示为 null,我不明白为什么。 (铬)

这是一个例子:

http://jsfiddle.net/PeSqR/

var href = "http://twitter.github.io/bootstrap/assets/css/bootstrap.css";

var link = document.createElement('link');
link.setAttribute('href', href);
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');

var intervalId = setInterval(
    function(){
        try{
            //console.log(link.sheet);
            //console.log(link.sheet.cssRules);
            if(link.sheet && link.sheet.cssRules.length){
                clearInterval(intervalId);
                clearTimeout(timeoutId);
            }
        }
        catch(e){
            //console.log('err...' + e.message);
        }
    },
10);

var timeoutId = setTimeout(
    function(){
        clearInterval(intervalId);
        clearTimeout(timeoutId);
        alert('ERROR');
    },
5000);

document.getElementsByTagName('head')[0].appendChild(link);

感谢您的帮助。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    最好的办法是对link.sheet 进行空检查,因为尝试访问link.sheet.cssRules 属性会返回此错误:

    [异常...“操作不安全。”代码:“18” nsresult:“0x80530012(SecurityError)”位置:“”]

    试试这个检查:

    if (link.sheet != null)
    

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 2015-04-07
      • 2011-05-26
      • 2017-01-25
      相关资源
      最近更新 更多