使用回调在 Chrome 中动态加载样式表

Dynamically load stylesheet in Chrome with callback

本文关键字:动态 加载 样式 Chrome 回调      更新时间:2023-09-26

http://www.phpied.com/when-is-a-stylesheet-really-loaded/

使用此解决方案非常适合加载带有回调的样式表,Chrome 除外。

在Chrome(v18)中,我仍然可以看到正在应用的CSS,这搞砸了其他一些取决于动态加载CSS的高度和宽度设置的功能。

有什么想法吗???

谢谢!

在WebKit中,您可以轮询对document.styleSheets的更改,这里有一个在lazyload中执行此操作的函数(取自 https://github.com/rgrove/lazyload/blob/master/lazyload.js)

或者只是使用该插件,它也可以:)

function pollWebKit() {
    var css = pending.css, i;
    if (css) {
      i = styleSheets.length;
      // Look for a stylesheet matching the pending URL.
      while (--i >= 0) {
        if (styleSheets[i].href === css.urls[0]) {
          finish('css');
          break;
        }
      }
      pollCount += 1;
      if (css) {
        if (pollCount < 200) {
          setTimeout(pollWebKit, 50);
        } else {
          // We've been polling for 10 seconds and nothing's happened, which may
          // indicate that the stylesheet has been removed from the document
          // before it had a chance to load. Stop polling and finish the pending
          // request to prevent blocking further requests.
          finish('css');
        }
      }
    }
  }