Skip to content

Commit

Permalink
Append scripts after boilerplate if it is present
Browse files Browse the repository at this point in the history
  • Loading branch information
schlessera committed Jun 17, 2021
1 parent 072a3fa commit d8269c2
Showing 1 changed file with 47 additions and 13 deletions.
60 changes: 47 additions & 13 deletions src/Optimizer/Transformer/AutoExtensions.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,19 +207,7 @@ private function removeUnneededExtensions(Document $document, $extensionScripts)
*/
private function renderExtensionScripts(Document $document, array $extensionScripts)
{
$referenceNode = $document->viewport;

if (!$referenceNode) {
$referenceNode = $document->charset;
}

if (
$referenceNode
&& $referenceNode->nextSibling instanceof Element
&& $referenceNode->nextSibling->hasAttribute(Attribute::AMP_BOILERPLATE)
) {
$referenceNode = $referenceNode->nextSibling;
}
$referenceNode = $this->getExtensionScriptsReferenceNode($document);

foreach ($extensionScripts as $extensionScript) {
if ($referenceNode && $referenceNode->nextSibling) {
Expand All @@ -235,6 +223,52 @@ private function renderExtensionScripts(Document $document, array $extensionScri
}
}

/**
* Get the reference node to attach extension scripts to.
*
* @param Document $document Document to look for the reference node in.
* @return Element|null Reference node to use, or null if not found.
*/
private function getExtensionScriptsReferenceNode(Document $document)
{
$referenceNode = $document->viewport ?: $document->charset;

if (! $referenceNode instanceof Element) {
$referenceNode = $document->head->firstChild;
}

if (! $referenceNode instanceof Element) {
return null;
}

// Try to detect the boilerplate style so we can append the scripts after that.
$remainingNode = $referenceNode->nextSibling;
while ($remainingNode) {
if (! $remainingNode instanceof Element) {
$remainingNode = $remainingNode->nextSibling;
continue;
}

if (
$remainingNode->tagName === Tag::STYLE
&& $remainingNode->hasAttribute(Attribute::AMP_BOILERPLATE)
) {
$referenceNode = $remainingNode;
} elseif (
$remainingNode->tagName === Tag::NOSCRIPT
&& $remainingNode->firstChild instanceof Element
&& $remainingNode->firstChild->tagName === Tag::STYLE
&& $remainingNode->firstChild->hasAttribute(Attribute::AMP_BOILERPLATE)
) {
$referenceNode = $remainingNode;
}

$remainingNode = $remainingNode->nextSibling;
}

return $referenceNode;
}

/**
* Maybe add a required extension to the list of extension scripts.
*
Expand Down

0 comments on commit d8269c2

Please sign in to comment.