The following code utilize DOM Mutation Event DOMNodeInserted
to detect the existence of the body
element and wrap its innerHTML
into a wrapper.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function DOMmanipulation() {
if (document.body) {
document.removeEventListener('DOMNodeInserted', DOMmanipulation);
// DOM manipulation start
document.body.innerHTML = '<div class="wrapper">' + document.body.innerHTML + '</div>';
// DOM manipulation end
}
}
document.addEventListener('DOMNodeInserted', DOMmanipulation);
</script>
</head>
<body>
<p>Lorem ipsum dolor sit amet.</p>
</body>
</html>
And despite the success of the wrapping, there is an error shows that a node was not found. This answer of a question explained that it is because when jQuery had been loaded, it added a div
element into the body to do some tests, but it failed to remove that div
element because that element has been wrapped into the wrapper so that it's not a child element of body anymore.
The above experiment tells us that DOMNodeInserted
event is faster than jQuery's tests because jQuery's test element (div
) got wrapped before it can be removed by jQuery.
Now the following code can achieve the same manipulation, and it's using the newly introduced DOM Mutation Observers. As of this time (2012-07-11), it works only on Chrome 18 and higher.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var observer = new WebKitMutationObserver(function() {
if (document.body) {
observer.disconnect();
// DOM manipulation start
document.body.innerHTML = '<div class="wrapper">' + document.body.innerHTML + '</div>';
// DOM manipulation end
}
});
observer.observe(document, { subtree: true, childList: true });
</script>
</head>
<body>
<p>Lorem ipsum dolor sit amet.</p>
</body>
</html>
This codes didn't produce any error. That means jQuery is faster than DOM Mutation Observers, so it was able to remove its test element (div
) before that element can be wrapped into the wrapper.
From the above two experiments, we find that when it comes to execution speed:
- DOM Mutation Events > jQuery's tests
- jQuery's tests > DOM Mutation Observers
Can this result appropriately prove that DOM Mutation Observers is slower than DOM Mutation Events?