简体   繁体   中英

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. 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. I suppose it's because the style element doesn't support the load event, isn't it?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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