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
Edit
Report