【问题标题】:JS alert function executed before if condition modifying the DOM even though alert is inside if . Why?JS alert 函数在 if 条件修改 DOM 之前执行,即使 alert 在 if 中。为什么?
【发布时间】:2018-05-23 14:42:00
【问题描述】:

为什么在这个 jQuery 例子中,jsFiddle alert 函数在 jquery 修改 .parent 的背景之前执行,即使 if(p.css('background-color', 'yellow')) 是先评估的。

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

谢谢

【问题讨论】:

  • Why {...} alert function is executed before jquery modifying the .parent's background。不是因为window.alert 是模态的,所以在模态阻塞UI 之前UI 没有时间重绘。并且在 if 条件中设置 CSS 属性没有真正的用例意义,因为它总是被评估为真实值
  • p.css('background-color', 'yellow') 将颜色设置为黄色。因此在设置颜色后执行警报
  • 您可以将警报包装在 setTimeout 函数中,延迟它
  • 看看@JiiB 是什么意思:jsfiddle.net/5gahLa6w/1 使用超时,你将函数回调放在事件队列中,让浏览器首先重新绘制 UI
  • @VineetDesai 设置颜色后但在屏幕上绘制颜色之前执行警报

标签: javascript jquery


【解决方案1】:

当您修改 DOM 时,浏览器不会更新图形。只有当没有更多的 javascript 可以执行时,它才会这样做。这个过程称为回流。

基本上浏览器是这样工作的:

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
    │          │                                   │
    │          │                                   │
    └────◀─────┴─────────────────◀─────────────────┘

但是,根据定义,alert() 函数不等待重排并中断 javascript 的执行。

因此,当您将背景颜色更改为黄色时,会发生以下情况:

  1. DOM被修改,背景变为黄色
  2. 调用警报并显示警报对话框
  3. 其他部分的 javascript 会一直执行,直到没有其他内容可以执行
  4. 触发回流,浏览器最终将黄色背景绘制到屏幕上

Reflow 以这种方式进行优化。不断重绘所有内容可能会降低浏览器的速度,因此即使规范没有描述回流,微软、Mozilla、谷歌和苹果不断竞争成为最好的浏览器这一事实意味着随着时间的推移,回流变得越来越成为一个批处理过程。

【讨论】:

猜你喜欢
  • 2011-01-27
  • 1970-01-01
  • 2018-04-25
  • 2018-06-25
  • 2017-07-08
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 2015-03-05
相关资源
最近更新 更多