diff --git a/includes/class-amp-theme-support.php b/includes/class-amp-theme-support.php index d33e362945e..a7c78204a7f 100644 --- a/includes/class-amp-theme-support.php +++ b/includes/class-amp-theme-support.php @@ -1191,6 +1191,22 @@ public static function prepare_response( $response, $args = array() ) { $dom = AMP_DOM_Utils::get_dom( $response ); $head = $dom->getElementsByTagName( 'head' )->item( 0 ); + // Move anything after , such as Query Monitor output added at shutdown, to be moved before . + $body = $dom->getElementsByTagName( 'body' )->item( 0 ); + if ( $body ) { + while ( $dom->documentElement->nextSibling ) { + // Trailing elements after will get wrapped in additional elements. + if ( 'html' === $dom->documentElement->nextSibling->nodeName ) { + while ( $dom->documentElement->nextSibling->firstChild ) { + $body->appendChild( $dom->documentElement->nextSibling->firstChild ); + } + $dom->removeChild( $dom->documentElement->nextSibling ); + } else { + $body->appendChild( $dom->documentElement->nextSibling ); + } + } + } + // Make sure scripts from the body get moved to the head. if ( isset( $head ) ) { $xpath = new DOMXPath( $dom ); diff --git a/tests/test-class-amp-theme-support.php b/tests/test-class-amp-theme-support.php index 5b09c0b5269..aeffad14281 100644 --- a/tests/test-class-amp-theme-support.php +++ b/tests/test-class-amp-theme-support.php @@ -1102,7 +1102,7 @@ public function test_prepare_response() { - + + @@ -1118,6 +1119,9 @@ public function test_prepare_response() { + +
+ gets moved. + $this->assertRegExp( '#\s*
\s*\s*\s*\s*$#s', $sanitized_html ); + $prepare_response_args = array( 'enable_response_caching' => true, );