简体   繁体   English

在向文档动态添加CSS规则时等待样式被应用

[英]Wait for Styles to be Applied when Dynamically Adding CSS Rules to Document

Say I have a string representing a bunch of CSS rules I'd like to add to a document dynamically. 假设我有一个字符串,代表一串我想动态添加到文档中的CSS规则。 Something like this would do the trick: 这样的事情可以解决问题:

function loadCssRules(rules, doc, callback) {
  var styleElement = this.createElement("style", doc);
  styleElement.type = 'text/css';

  if (styleElement.styleSheet) {
    // IE < 11
    styleElement.styleSheet.cssText = rules;
  } else if (styleElement.sheet) {
    // IE >= 11
    styleElement.sheet.cssText = rules;
  } else {
    // Other browsers
    styleElement.innerHTML = rules;
  }

  if (callback) {
    styleElement.addEventListener('load', callback);
  }

  doc.getElementsByTagName("head")[0].appendChild(styleElement);
}

However, callback would never be called. 但是,永远不会调用callback I suppose it's because the style element doesn't support the load event, isn't it? 我想这是因为style元素不支持load事件,不是吗?

Is there anyway I could continue execution only after all new rules have been applied? 无论如何,只有应用了所有新规则后,我才能继续执行吗?

As far as I know, rules appliance are synchronous. 据我所知,规则设备是同步的。 I hope to be right, if that's the case, whis would work: 我希望是正确的,如果是这样的话,可以进行以下操作:

function loadCssRules(rules, doc, callback) {
  var styleElement = this.createElement("style", doc);
  ...    
    styleElement.innerHTML = rules;
  } 
  doc.getElementsByTagName("head")[0].appendChild(styleElement);
  if (callback) {
    callback();
  }
}

Hope this helps. 希望这可以帮助。 Cheers 干杯

After you add style tag the browser rebuild it stylesheet tree and reflow/repaint necessary layers , but this don't block user I/O where does javascript executes. 添加样式标签后,浏览器将重建它的stylesheet tree reflow/repaint必要的layers ,但这不会阻止user I/O在javascript中执行。 So styles and scripts will apply async. 因此样式和脚本将应用异步。

But if you will change size of any DOM elements in stylesheet rules javascript will be blocked while browser engine recalculate new size. 但是,如果您要更改样式表规则中任何DOM元素的大小,则JavaScript将在浏览器引擎重新计算新大小时被阻止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM