dkjain
dkjain

Reputation: 881

JS alert function executed before if condition modifying the DOM even though alert is inside if . Why?

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')
  }

jsFiddle

Thanks

Upvotes: 1

Views: 117

Answers (1)

slebetman
slebetman

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:

  1. DOM is modified and the background is changed to yellow
  2. Alert is called and the alert dialog is displayed
  3. Other bits of javascript is executed until there's nothing else to execute
  4. Reflow is triggered and the browser finally draws the yellow background to screen

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

Related Questions