Skip to content

Commit 31eeaa7

Browse files
author
Mateusz Krzeszowiak
committed
Adjust mechanism that moves all scripts to the end of the page
1 parent ecaa3b7 commit 31eeaa7

File tree

1 file changed

+26
-19
lines changed

1 file changed

+26
-19
lines changed

app/code/Magento/Theme/Controller/Result/JsFooterPlugin.php

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -40,25 +40,32 @@ public function __construct(ScopeConfigInterface $scopeConfig)
4040
public function beforeSendResponse(Http $subject)
4141
{
4242
$content = $subject->getContent();
43-
$script = [];
44-
if (is_string($content) && strpos($content, '</body') !== false) {
45-
if ($this->scopeConfig->isSetFlag(
46-
self::XML_PATH_DEV_MOVE_JS_TO_BOTTOM,
47-
ScopeInterface::SCOPE_STORE
48-
)
49-
) {
50-
$pattern = '#<script[^>]*+(?<!text/x-magento-template.)>.*?</script>#is';
51-
$content = preg_replace_callback(
52-
$pattern,
53-
function ($matchPart) use (&$script) {
54-
$script[] = $matchPart[0];
55-
return '';
56-
},
57-
$content
58-
);
59-
$subject->setContent(
60-
str_replace('</body', implode("\n", $script) . "\n</body", $content)
61-
);
43+
44+
$bodyClose = '</body';
45+
46+
if (is_string($content) && strpos($content, $bodyClose) !== false && $this->scopeConfig->isSetFlag(
47+
self::XML_PATH_DEV_MOVE_JS_TO_BOTTOM,
48+
ScopeInterface::SCOPE_STORE
49+
)) {
50+
$scripts = '';
51+
52+
$scriptOpen = '<script';
53+
$scriptClose = '</script>';
54+
55+
$scriptOpenPos = strpos($content, $scriptOpen);
56+
while ($scriptOpenPos !== false) {
57+
$scriptClosePos = strpos($content, $scriptClose, $scriptOpenPos);
58+
$script = substr($content, $scriptOpenPos, $scriptClosePos - $scriptOpenPos + strlen($scriptClose));
59+
60+
$scripts .= "\n" . $script;
61+
$content = str_replace($script, '', $content);
62+
// Script cut out, continue search from its position.
63+
$scriptOpenPos = strpos($content, $scriptOpen, $scriptOpenPos);
64+
}
65+
66+
if ($scripts) {
67+
$content = str_replace($bodyClose, $scripts . "\n" . $bodyClose, $content);
68+
$subject->setContent($content);
6269
}
6370
}
6471
}

0 commit comments

Comments
 (0)