DIV CSS 佈局教程網

JS 如何判斷 CSS 文件是否加載完畢
編輯:JavaScript綜合知識     

多數情況下我們不需要判斷 CSS 文件是否加載成功,但有時候這個功能確實必要。本文整理了相容各種瀏覽器的判斷方法。

IE 與 Opera:直接用 onload

這次 IE 做得不錯,可以直接透過 onload 處理 CSS 加載完成後的回呼:

// 代碼節選至 seajs
function styleOnload(node, callback) {
  // for IE6-9 and Opera
  if (node.attachEvent) {
    node.attachEvent('onload', callback);
    // NOTICE:
    // 1. "onload" will be fired in IE6-9 when the file is 404,
    //    but in this situation, Opera does nothing, so fallback to timeout.
    // 2. "onerror" doesn't fire in any browsers!
  }
}

Firefox 與 WebKit:輪詢 cssRules

在其他瀏覽器中判斷就沒那麼方便了。Firefox、WebKit 可以透過 node.sheet.cssRules 屬性是否存在來判斷,並需要用 setTimeout 間隔輪詢:

// 代碼節選至 seajs
function poll(node, callback) {
  if (callback.isCalled) {
    return;
  }
  var isLoaded = false;
  if (/webkit/i.test(navigator.userAgent)) { // webkit
    if (node['sheet']) {
      isLoaded = true;
    }
  }
  // for Firefox
  else if (node['sheet']) {
    try {
      if (node['sheet'].cssRules) {
        isLoaded = true;
      }
    } catch (ex) {
      // NS_ERROR_DOM_SECURITY_ERR
      if (ex.code === 1000) {
        isLoaded = true;
      }
    }
  }
  if (isLoaded) {
    setTimeout(function () { callback(); }, 1); // give time to render
  } else {
    setTimeout(function () { poll(node, callback); }, 1);
  }
}

SeaJS 的整合寫法

function styleOnload(node, callback) {
  // for IE6-9 and Opera
  if (node.attachEvent) {
    node.attachEvent('onload', callback);
  }
  // polling for Firefox, Chrome, Safari
  else {
    setTimeout(function () { poll(node, callback); }, 0); // for cache
  }
}

動態建立 LINK 並監聽

function createLink(cssURL, lnkId, charset, media) {
  var head = document.getElementsByTagName('head')[0],
    linkTag = null;
  if (!cssURL) { return false; }
  linkTag = document.createElement('link');
  linkTag.setAttribute('id', (lnkId || 'dynamic-style'));
  linkTag.setAttribute('rel', 'stylesheet');
  linkTag.setAttribute('charset', (charset || 'utf-8'));
  linkTag.setAttribute('media', (media || 'all'));
  linkTag.setAttribute('type', 'text/css');
  linkTag.href = cssURL;
  head.appendChild(linkTag);
}
function loadcss() {
  var styleNode = createLink('/wp-content/themes/BlueNight/style.css');
  styleOnload(styleNode, function () {
    alert("loaded");
  });
}

另一種思路:輪詢樣式是否生效

Diego Perini 的 cssready.js 提供另一種方案,透過輪詢 link 節點的 rules 是否可讀來判斷:

function cssReady(fn, link) {
  var d = document,
    t = d.createStyleSheet,
    r = t ? 'rules' : 'cssRules',
    s = t ? 'styleSheet' : 'sheet',
    l = d.getElementsByTagName('link');
  link || (link = l[l.length - 1]);
  function check() {
    try {
      return link && link[s] && link[s][r] && link[s][r][0];
    } catch (e) {
      return false;
    }
  }
  (function poll() {
    check() && setTimeout(fn, 0) || setTimeout(poll, 100);
  })();
}

此外,Facebook 的做法是在動態建立的 CSS 中包含一個固定樣式(如 #loadcssdom,高度 1px),再動態建立一個套用該樣式的 DOM 對象,然後輪詢該對象是否已有 1px 高度。可見判斷 CSS 是否加載完畢,目前確實不容易,只能依瀏覽器特性分別處理。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved