2010-09-25 104 views
7

加载我有一个函数做使用javascript以下:如何检查是否外部(跨域)CSS文件使用Javascript

  1. 创建链接元素和HREF =设定cssFile。
  2. 将链接元素插入到头标签中。
  3. 创建一个div元素。
  4. 使用setAttribute设置类名称
  5. appendChild div的正文。
  6. 现在使用document.defaultView.getComputedStyle(divElement, null)[cssRule]获取CSS规则值。

现在getComputedStyle将返回默认值,如果我之前getComputedStyle通话断点使用Firebug等待,然后返回从注入的CSS的CSS规则。

问候,
穆奈姆

回答

8

这实际上是我做过什么。

为了确保加载特定的CSS文件,我在CSS文件的末尾添加了一个样式。例如:

#ensure-cssload-8473649 { 
    display: none 
} 

现在我有一个JavaScript函数时,上面的样式加载页面时会触发指定的回调:

var onCssLoad = function (options, callback) { 
    var body = $("body"); 
    var div = document.createElement(constants.TAG_DIV); 
    for (var key in options) { 
     if (options.hasOwnProperty(key)) { 
      if (key.toLowerCase() === "css") { 
       continue; 
      } 
      div[key] = options[key]; 
     } 
    } 

    var css = options.css; 
    if (css) { 
     body.appendChild(div); 
     var handle = -1; 
     handle = window.setInterval(function() { 
      var match = true; 
      for (var key in css) { 
       if (css.hasOwnProperty(key)) { 
        match = match && utils.getStyle(div, key) === css[key]; 
       } 
      } 

      if (match === true) { 
       window.clearTimeout(handle); 
       body.removeChild(div); 
       callback(); 
      } 
     }, 100); 
    } 
} 

而且这是我用上面的功能:

onCssLoad({ 
    "id": "ensure-cssload-8473649", 
    css: { 
     display: "none" 
    } 
}, function() { 
    // code when you want to execute 
    // after your CSS file is loaded 
}); 

这里的第一个参数采用options其中id是要检查的测试风格和css属性来验证从CSS加载的内容。

+0

如果我们不想自己加载css,这个解决方案仍然是最好的。 (例如,如果我们使用装载机) – Offirmo 2013-03-20 15:02:21

4

我假设,因为你需要动态地创建样式表的URL你这样做。

夫妇选项浮现在脑海中:

1)创建URL服务器端和完全避免这个问题。

2)使用setTimeout检查样式是否已被加载,并每隔20ms检查一次,直到getComputedStyle返回所需的值。

我不喜欢#2 ...但它是一个选项。如果您使用#2,请确保即使有异常也要清除超时。

9

您可以创建动态CSS链接并使用普通的ajax调用以纯文本方式获取CSS。

然后用这个来加载CSS:

function loadCss(cssText, callback){ 
    var style = document.createElement('style'); 
    style.type='text/css'; 
    if(callBack != undefined){ 
     style.onload = function(){ 
      callBack(); 
     }; 
    } 
    style.innerHTML = cssText; 
    head.appendChild(style); 
} 

而且使用这样的:

loadCss(ajaxResponseText, function(){ 
    console.log("yaay css loaded, now i can access css defs"); 
}) 
+1

+1了这个解决方案。我更喜欢它,我假设所有浏览器都可以解释一个动态添加的样式标签(还没有尝试过)。 – 2010-09-25 14:49:45

+1

感谢您的解决方案!但有一件事,我忘了在问题中提到,这是我的CSS是在其他域...意思是,没有Ajax响应的跨浏览器问题 – 2010-09-25 14:57:08

+0

@Munim:如果CSS是在另一个域上,尝试添加'link'标记(头)与适当的类型,rel和href和onload函数。让我知道它是否有效。 – letronje 2010-09-25 15:22:57

2

以下是似乎适用于所有浏览器的解决方案。

function loadCss(fileUrl) { 
    // check for css file type 
    if (fileUrl.indexOf(".css")==fileUrl.length-4) { 
    // Create link element 
    var fileref=document.createElement("link"); 
    fileref.setAttribute("rel", "stylesheet"); 
    fileref.setAttribute("type", "text/css"); 
    fileref.setAttribute("href", fileUrl); 
    if (typeof fileref!="undefined") { 
     // remove the . if this is a relative link 
     if(fileUrl.indexOf('.')==0) { 
     fileUrl = fileUrl.substr(1); 
    } 
    // generate the full URL to use as the fileId 
     var pathname = window.location.pathname; 
    var pathUrl = pathname.substr(0,pathname.lastIndexOf("/")); 
    var fileId = window.location.protocol + "//" + window.location.host + pathUrl + fileUrl; 
     // append the newly created link tag to the head of the document 
     document.getElementsByTagName("head")[0].appendChild(fileref); 

    // begin checking for completion (100ms intervals up to 2000ms) 
    this.checkCSSLoaded(fileId,100,0,2000); 

    } else throw 'INVALID_CSS_ERROR'; 
    } else throw 'INVALID_CSS_ERROR'; 
} 

function checkCSSLoaded(cssHref,milliPerCheck,milliPerCount,milliTimeout) { 
    // Look through all sheets and try to find the cssHref 
    var atSheet = -1; 
    var sheetLength = document.styleSheets.length; 
    while(++atSheet < sheetLength) { 
if(cssHref == document.styleSheets[atSheet].href) { 
     // If found dispatch and event or call a procedure 
     /* Do whatever is next in your code here */ 
    return; 
} 
    } 
    // check for timeout 
    if(milliCount > milliTimeout) { 
    alert('INVALID_CSS_ERROR::'+" ("+cssHref+"+ not found!"); 
    /* Do whatever happens if timeout is reached here */ 
return; 
    } 
    // else keep trying 
    setTimeout(checkCSSLoaded ,milliPerCheck, cssHref, milliPerCheck, milliCount+millPerCheck, milliTimeout); 
} 

本质上讲,我们

  1. 创建一个链接标签。
  2. 设置其属性,所以它知道它的样式表的链接标签
  3. 以这样一种方式,它永远是完整的文件URL
  4. 附加的链接标签文件头部的头部创建一个文件编号
  5. 进行连续测试,看看(stylesheet.href == FILEID)开始存在
    • 如果找到了做别的事情,如果超时做别的事情继续检查
0

使用document.styleSheets检查一个css是否加载是错误的,因为只要一个css链接被添加到DOM中,即使它尚未加载,它也可以从document.styleSheets获得。

向CSS添加一个标记也是一件难事。

正确的解决办法是听onload事件:

var loadedCss = {}; 
    cssHref = "http://www.foo.com/bar.css"; 
    css = document.createElement("link"); 
    css.setAttribute("rel", "stylesheet"); 
    css.setAttribute("type", "text/css"); 
    css.setAttribute("href", cssHref); 
    css.onload = function(){ 
     loadedCss[cssHref] = true; 
    } 
    document.getElementsByTagName("head")[0].appendChild(css); 


    function isCssLoaded(url) { 
     return loadCss[url]; 
    } 
+0

之前,你敲它..试试看 - 本哈珀 – dRoneBrain 2014-03-14 18:36:42

相关问题