2013-05-10 52 views
0

我試圖動態加載樣式表,並檢查它什麼時候已經準備好了cssRules屬性,但它是空的,我看不出爲什麼。 (鉻)動態加載樣式表,cssRules出現爲空

下面是一個例子:

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

感謝您的幫助。

回答

0

你最好的選擇將是剛剛在link.sheet運行空支票試圖訪問link.sheet.cssRules屬性返回該錯誤:

[Exception... "The operation is insecure." code: "18" nsresult: "0x80530012 (SecurityError)" location: ""]

試試這個檢查來代替:

if (link.sheet != null)