javascript - 使用 yepnope,我怎么知道 css 资源是否加载成功?

标签 javascript css yepnope

我正在开发一个 web 应用程序,供一家拥有严格(且不断发展的)防火墙的公司内部使用。

我正在使用 yepnope.js/Modernizr.load 从 CDN 加载带有回退的 js 和 css 文件。

但是我怎么知道 css 是否加载成功呢?有没有办法测试 css 的成功加载和激活?

最佳答案

感谢@Morpheus 的提示,这是一个解决方案:

首先,为了不依赖于任何东西(jQuery 等),我们需要定义 2 个函数:

  • 获取元素的 css 属性:

来自 http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/

function getStyle(oElm, strCssRule) {
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
},
  • 另一个创建隐藏 DOM 元素并测试其 css 属性的方法:

来自 https://stackoverflow.com/a/8122005/587407

function test_css(element_name, element_classes, expected_styles, rsrc_name, callback) {
  // create an element of given type
  var elem = document.createElement(element_name);
  // immediately hide it
  elem.style.display = 'none';
  // give it the class(es)
  for (var i = 0; i < element_classes.length; i++) {
    elem.className = elem.className + " " + element_classes[i];
  }
  // and add it to the DOM
  document.body.appendChild(elem);

  // test the given properties
  // it happens (~1/3 times in local)
  // that the css takes a few ms to apply.
  // so we need a function that we can try directly first
  // and retry again later in case of failure
  var handle = -1;
  var try_count = 0;
  var test_function = function() {
    var match = true; // so far
    try_count++;
    for (var key in expected_styles) {
      console.log("[CSS loader] testing " + rsrc_name + " css : " + key + " = '" + expected_styles[key] + "', actual = '" + get_style_of_element(elem, key) + "'");
      if(get_style_of_element(elem, key) === expected_styles[key]) {
        match = match && true;
      } else {
        console.error("[CSS loader] css " + rsrc_name + " test failed (not ready yet ?) : " + key + " = " + expected_styles[key] + ", actual = " + get_style_of_element(elem, key) );
        match = false;
      }
    }

    if (match === true || try_count >= 3) {
      if (handle >= 0)
        window.clearTimeout(handle);
      // remove our test element from the DOM
      document.body.removeChild(elem);
      if (!match)
        console.error("[CSS loader] giving up on css " + rsrc_name + "..." );
      else
        console.log("[CSS loader] css " + rsrc_name + " load success !" );
      callback(rsrc_name, match);
    }
    return match;
  }

  // use and program the function
  if(! test_function() ) {
    console.info("" + rsrc_name + " css test failed, programming a retry...");
    handle = window.setInterval(test_function, 100);
  }
}

请注意,由于 css 的延迟加载,前面的函数比较棘手。

我们现在可以像这样使用 yepnope 了:

{
  load: { 'bootstrap-css': 'http//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css' },
  callback: function (url, result, key) {
  // here for bootstrap, I test presence of .span1 class
  test_css('span', [ 'span1' ], { 'width': '60px' }, function(match) {
    if( match )  {
      // it worked !
    }
    else {
      // ... fallback on another CDN or local rsrc...
    }
  }
}

关于javascript - 使用 yepnope,我怎么知道 css 资源是否加载成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15519937/

相关文章:

javascript - Modernizr.load (Yepnope) 是否用于 <head>

javascript - 如果启动后互联网可用,如何使用预加载器加载外部 JavaScript?

php - 通过 js 框架组织 JQuery 片段

html - 将字体粗细更改为粗体会无意中改变元素的宽度

html - 溢出时调整中间 div 以填充 div 之间的空间 :hidden; doesn't work

jquery - 有没有 jquery 可以让 css Shadow-roundedcorners 在 IE6 及以上版本上工作

javascript - 使用 YepNope/Modernizr 加载外部 Google 字体样式表

javascript - Angular Js - 检查内部 radio 输入时格式化标签

javascript - 带进度条的 slider 上的 Jquery setInterval

javascript - 如何通过CloudFront实现分段上传?