MutationObserver
api을 사용하면 DOM
변경 사항을 감지 할 수 있습니다.
다음은 브라우저가 원하는 것을 기반으로 Dom Changed
이벤트를 트리거하는지 확인하는 데 사용할 수있는 예제입니다.
여기에 jquery로 text('...')
과 jquery를 사용하지 않는 el.textContent
이 있습니다. 크롬 55
-
$(document).ready(function() {
$('#btn1').click(function() {
console.log('text changed - jquery');
$('#a1').text('text 1');
});
$('#btn2').click(function() {
console.log('text changed - textContent');
$('#a1')[0].textContent = $('#a1')[0].textContent
});
$('#btn3').click(function() {
console.log('class changed');
$('#a1').attr('class', 'cls' + Math.floor(Math.random() * 10));
});
});
var target = $('#a1')[0];
// create an observer instance
var observer = new MutationObserver(function(mutations) {
var changed = false;
mutations.forEach(function(mutation) {
// You can check the actual changes here
});
console.log('Dom Changed');
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
.cls1 {
border: 1px solid red;
}
.cls2 {
border: 1px solid pink;
}
.cls3 {
border: 1px solid cyan;
}
.cls4 {
border: 1px solid darkgreen;
}
.cls5 {
border: 1px solid orange;
}
.cls6 {
border: 1px solid darkred;
}
.cls7 {
border: 1px solid black;
}
.cls8 {
border: 1px solid yellow;
}
.cls9 {
border: 1px solid blue;
}
.cls10 {
border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1" class="cls1">text 1</div>
<button id="btn1">Change text - jquery (keep original)</button><br />
<button id="btn2">Change text - textContent (keep original)</button><br />
<button id="btn3">Change class (real change)</button>
만 setAttribute()
및 jQuery를 text()
Dom Change
이벤트를 트리거.
- Firefox 50에서 모든 것이
Dom Change
이벤트를 트리거했습니다.
- Edge 38에서 모든 것이
Dom Change
이벤트를 트리거했습니다.
요즘 브라우저는 매우 똑똑합니다. 변경 사항이없는 경우 리플 로우가 발생하지 않으며 현명한 표시가됩니다. 그리고 그때도 다시 칠하기는 영향을받는 화면 부분에만 적용됩니다. –
* 공간을 낭비하고 있습니다. * 예, 공간은 요즘 프리미엄급이며, 저의 데스크탑에는 32GB의 RAM 만 있습니다. –
@torazaburo 큰 SPA에있는 모든 바운드 값의 사본을 휴대 기기에 저장하는 것은 비용이 많이 들며, 자주 바뀌면 수집해야하는 많은 쓰레기를 만들어 프레임 률을 엉망으로 만듭니다. 큰 효과는 아니지만, 그것을 수행 할 때 제로 포인트가 있다면 여기에서이기는 것이 여전히있을 수 있습니다. – Anders