Reputation: 881
Why in this jQuery example, jsFiddle alert
function is executed before jquery
modifying the .parent
's background even though if(p.css('background-color', 'yellow'))
is evaluated first.
CSS
.parent {
width: 400px;
padding: 10px;
margin: 10px;
border: 1px solid;
background-color: green;
}
HTML
<div class="parent">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti qui esse illum, unde labore. Repellendus sunt, quidem eligendi aliquid architecto animi officia itaque ducimus impedit, enim laudantium quis, cupiditate optio.</div>
jQuery
var p = $('.parent');
p.css('border', '3px solid blue');
if(p.css('background-color', 'yellow')){
alert('cool')
} else {
alert( 'Not COOL')
}
Thanks
Upvotes: 1
Views: 117
Reputation: 113906
The browser does not update the graphics when you modify the DOM. It only does so when there's no more javascript to execute. This process is called reflow.
Basically this is how the browser works:
Event loop
┌──────────┐
│ │
│ │
│ ▼
│ check if there's any new ───────▶ parse data
│ data on the network │
│ │ │
│ ▼ │
│ check if we need to execute ◀─────────┘
│ any javascript ──────────────────▶ execute
│ │ javascript
│ ▼ │
│ check if we need to ◀────────────────┘
│ redraw the page ──────────────▶ redraw page
│ │ │
│ │ │
└────◀─────┴─────────────────◀─────────────────┘
However, by definition the alert()
function does not wait for reflow and interrupts the execution of javascript.
Therefore when you change the background color to yellow the following happens:
Reflow behaves this way as an optimization. Constantly redrawing everything potentially slows down browsers so even if reflow isn't described by the specification the very fact that Microsoft, Mozilla, Google and Apple are constantly competing to be the best browser means the over time reflow becomes more and more a batch process.
Upvotes: 3