简体   繁体   中英

Any hidden advantage of assigning a variable to itself in javascript? “force reflow”?

I was doing code inspection on a js code base and I got some variables assigned to their-selves. I found one strange assignment in ui-bootstrap-tpls-0.5.0.js:445 which is:

nextSlide.$element[0].offsetWidth = nextSlide.$element[0].offsetWidth; //force reflow

What they mean with the note: // force reflow ?

In general, is there any advantage of variable self-assignment in JS ? DOM nodes?

You can read more about reflow in Rendering: repaint, reflow/relayout, restyle

Essentially a 'reflow' is something that initiates a 'layout' update in the browsers render model. This can be useful if you know that a change has occurred that should require the page to be re-rendered, but for some reason this might not have happened.

Specifics about what can or should cause a reflow, or when the layout will actually be recalculated, are down to each browser implementation. From the article linked above:

Since the reflows and repaints associated with render tree changes are expensive, the browsers aim at reducing the negative effects. [...]. The browser will setup a queue of the changes your scripts require and perform them in batches.

So you may find a situation where you are expecting a reflow/layout to have occurred, but the browsers layout batch policy has prevented it from occurring (yet). This seems to be what the original code is trying to solve.

This pattern is also used sometimes to refresh web pages, example :

// refresh the current web page 
document.location.href = document.location.href;

Or used to redraw HTML5 canvas , for example :

// .. draw some pretty cool shapes here 
// force canvas to redraw
canvas.width = canvas.width;

Hope this helps.

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