3

I load some style.css dynamically in javascript. when the style is loaded, I'll do some calculation that depends on the styles. The code is like this:

link = document.createElement('link');
link.href = 'sheety.css';
link.rel = 'stylesheet';
document.head.appendChild(link);
link.onload = function(){
    //some code
    //here, I can't the the correct style sometime.
    //but most of the time, I can get the correct style
    setTimeout(function(){
        //here, I can also get the correct style
    }, 1000);
};

So, my question is: when does the style is applied successfully?
If I modify the element's position(width, height), can I get the correct value instant, or I must wait some time to let the browser do something by using like setTimeout() function?


I read some resources that says: call dom.getComputedStyle will cause a browser reflow. I indeed call this method, but I still get the wrong width/height of the DOM.

When I debug the JS code in chrome, I can see that the style is not applied at the break point (from the style tab in chrome developer tools).

Taryn
  • 242,637
  • 56
  • 362
  • 405
qlqllu
  • 221
  • 2
  • 11

1 Answers1

0

Once the style sheet is loaded, a CSSOM or CSSObjectModel is generated. Along with the DOM, the CSSOM is rasterized by a rasterizer and applied (in Chrome, done by Skia).

A style can be said to be applied successfully when a browser completes a reflow or a repaint. We can force the browser for a redraw using many techniques:

  1. element.hide().show(); #using jQuery
  2. Inserting a node into the DOM and removing it.

These techniques are better explained in a similar question.

Community
  • 1
  • 1
MIdhun Krishna
  • 1,739
  • 1
  • 13
  • 31