Skip to content

Adjust critical CSS extraction and placement #27211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 41 additions & 27 deletions app/code/Magento/Theme/Controller/Result/AsyncCssPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,39 +39,53 @@ public function __construct(ScopeConfigInterface $scopeConfig)
*/
public function beforeSendResponse(Http $subject): void
{
$content = $subject->getContent();
$content = (string)$subject->getContent();

if (\is_string($content) && strpos($content, '</body') !== false && $this->scopeConfig->isSetFlag(
$headClose = '</head>';

if (strpos($content, $headClose) !== false && $this->scopeConfig->isSetFlag(
self::XML_PATH_USE_CSS_CRITICAL_PATH,
ScopeInterface::SCOPE_STORE
)) {
$cssMatches = [];
// add link rel preload to style sheets
$content = preg_replace_callback(
'@<link\b.*?rel=("|\')stylesheet\1.*?/>@',
function ($matches) use (&$cssMatches) {
$cssMatches[] = $matches[0];
preg_match('@href=("|\')(.*?)\1@', $matches[0], $hrefAttribute);
$href = $hrefAttribute[2];
if (preg_match('@media=("|\')(.*?)\1@', $matches[0], $mediaAttribute)) {
$media = $mediaAttribute[2];
}
$media = $media ?? 'all';
$loadCssAsync = sprintf(
'<link rel="preload" as="style" media="%s"' .
' onload="this.onload=null;this.rel=\'stylesheet\'"' .
' href="%s" />',
$media,
$href
);
$styles = '';
$styleOpen = '<link';
$styleClose = '>';
$styleOpenPos = strpos($content, $styleOpen);

while ($styleOpenPos !== false) {
$styleClosePos = strpos($content, $styleClose, $styleOpenPos);
$style = substr($content, $styleOpenPos, $styleClosePos - $styleOpenPos + strlen($styleClose));

if (!preg_match('@rel=["\']stylesheet["\']@', $style)) {
// Link is not a stylesheet, search for another one after it.
$styleOpenPos = strpos($content, $styleOpen, $styleClosePos);
continue;
}
// Remove the link from HTML to add it before </head> tag later.
$content = str_replace($style, '', $content);

return $loadCssAsync;
},
$content
);
preg_match('@href=("|\')(.*?)\1@', $style, $hrefAttribute);
$href = $hrefAttribute[2];

if (preg_match('@media=("|\')(.*?)\1@', $style, $mediaAttribute)) {
$media = $mediaAttribute[2];
}
$media = $media ?? 'all';

$style = sprintf(
'<link rel="stylesheet" media="print"' .
' onload="this.onload=null;this.media=\'%s\'"' .
' href="%s">',
$media,
$href
);
$styles .= "\n" . $style;
// Link was cut out, search for the next one at its former position.
$styleOpenPos = strpos($content, $styleOpen, $styleOpenPos);
}

if (!empty($cssMatches)) {
$content = str_replace('</body', implode("\n", $cssMatches) . "\n</body", $content);
if ($styles) {
$content = str_replace($headClose, $styles . "\n" . $headClose, $content);
$subject->setContent($content);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,26 +67,60 @@ public function sendResponseDataProvider(): array
{
return [
[
"content" => "<body><h1>Test Title</h1>" .
"<link rel=\"stylesheet\" href=\"css/critical.css\" />" .
"<p>Test Content</p></body>",
"content" => "<head><link rel=\"stylesheet\" href=\"css/async.css\">" .
"<style>.critical-css{}</style>" .
"</head>",
"flag" => true,
"result" => "<body><h1>Test Title</h1>" .
"<link rel=\"preload\" as=\"style\" media=\"all\"" .
" onload=\"this.onload=null;this.rel='stylesheet'\" href=\"css/critical.css\" />" .
"<p>Test Content</p>" .
"<link rel=\"stylesheet\" href=\"css/critical.css\" />" .
"\n</body>"
"result" => "<head><style>.critical-css{}</style>\n" .
"<link " .
"rel=\"stylesheet\" media=\"print\" onload=\"this.onload=null;this.media='all'\" " .
"href=\"css/async.css\">\n" .
"</head>",
],
[
"content" => "<body><p>Test Content</p></body>",
"content" => "<head><link rel=\"stylesheet\" href=\"css/async.css\">" .
"<link rel=\"preload\" href=\"other-file.html\">" .
"</head>",
"flag" => true,
"result" => "<head><link rel=\"preload\" href=\"other-file.html\">\n" .
"<link " .
"rel=\"stylesheet\" media=\"print\" onload=\"this.onload=null;this.media='all'\" " .
"href=\"css/async.css\">\n" .
"</head>",
],
[
"content" => "<head><link rel=\"stylesheet\" href=\"css/async.css\">" .
"<link rel=\"preload\" href=\"other-file.html\">" .
"</head>",
"flag" => false,
"result" => "<body><p>Test Content</p></body>"
"result" => "<head><link rel=\"stylesheet\" href=\"css/async.css\">" .
"<link rel=\"preload\" href=\"other-file.html\">" .
"</head>",
],
[
"content" => "<body><p>Test Content</p></body>",
"content" => "<head><link rel=\"stylesheet\" href=\"css/first.css\">" .
"<link rel=\"stylesheet\" href=\"css/second.css\">" .
"<style>.critical-css{}</style>" .
"</head>",
"flag" => true,
"result" => "<body><p>Test Content</p></body>"
"result" => "<head><style>.critical-css{}</style>\n" .
"<link " .
"rel=\"stylesheet\" media=\"print\" onload=\"this.onload=null;this.media='all'\" " .
"href=\"css/first.css\">\n" .
"<link " .
"rel=\"stylesheet\" media=\"print\" onload=\"this.onload=null;this.media='all'\" " .
"href=\"css/second.css\">\n" .
"</head>",
],
[
"content" => "<head><style>.critical-css{}</style></head>",
"flag" => false,
"result" => "<head><style>.critical-css{}</style></head>"
],
[
"content" => "<head><style>.critical-css{}</style></head>",
"flag" => true,
"result" => "<head><style>.critical-css{}</style></head>"
]
];
}
Expand Down Expand Up @@ -121,18 +155,37 @@ public function testBeforeSendResponse($content, $isSetFlag, $result): void
$this->plugin->beforeSendResponse($this->httpMock);
}

/**
* Data Provider for testBeforeSendResponseIfGetContentIsNotAString()
*
* @return array
*/
public function ifGetContentIsNotAStringDataProvider(): array
{
return [
'empty_array' => [
'content' => []
],
'null' => [
'content' => null
]
];
}

/**
* Test BeforeSendResponse if content is not a string
*
* @param string $content
* @return void
* @dataProvider ifGetContentIsNotAStringDataProvider
*/
public function testIfGetContentIsNotAString(): void
public function testBeforeSendResponseIfGetContentIsNotAString($content): void
{
$this->httpMock->expects($this->once())
->method('getContent')
->willReturn([]);
->willReturn($content);

$this->scopeConfigMock->expects($this->any())
$this->scopeConfigMock->expects($this->never())
->method('isSetFlag')
->with(
self::STUB_XML_PATH_USE_CSS_CRITICAL_PATH,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
<argument name="criticalCssViewModel" xsi:type="object">Magento\Theme\Block\Html\Header\CriticalCss</argument>
</arguments>
</block>
<block name="css_rel_preload_script" ifconfig="dev/css/use_css_critical_path" template="Magento_Theme::js/css_rel_preload.phtml"/>
</referenceBlock>
<referenceContainer name="after.body.start">
<block class="Magento\Framework\View\Element\Js\Components" name="head.components" as="components" template="Magento_Theme::js/components.phtml" before="-"/>
Expand Down

This file was deleted.