|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\Theme\Controller\Result; |
| 9 | + |
| 10 | +use Magento\Framework\App\Config\ScopeConfigInterface; |
| 11 | +use Magento\Store\Model\ScopeInterface; |
| 12 | +use Magento\Framework\App\Response\Http; |
| 13 | + |
| 14 | +/** |
| 15 | + * Plugin for asynchronous CSS loading. |
| 16 | + */ |
| 17 | +class AsyncCssPlugin |
| 18 | +{ |
| 19 | + private const XML_PATH_USE_CSS_CRITICAL_PATH = 'dev/css/use_css_critical_path'; |
| 20 | + |
| 21 | + /** |
| 22 | + * @var ScopeConfigInterface |
| 23 | + */ |
| 24 | + private $scopeConfig; |
| 25 | + |
| 26 | + /** |
| 27 | + * @param ScopeConfigInterface $scopeConfig |
| 28 | + */ |
| 29 | + public function __construct(ScopeConfigInterface $scopeConfig) |
| 30 | + { |
| 31 | + $this->scopeConfig = $scopeConfig; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Load CSS asynchronously if it is enabled in configuration. |
| 36 | + * |
| 37 | + * @param Http $subject |
| 38 | + * @return void |
| 39 | + */ |
| 40 | + public function beforeSendResponse(Http $subject): void |
| 41 | + { |
| 42 | + $content = $subject->getContent(); |
| 43 | + |
| 44 | + if (strpos($content, '</body') !== false && $this->scopeConfig->isSetFlag( |
| 45 | + self::XML_PATH_USE_CSS_CRITICAL_PATH, |
| 46 | + ScopeInterface::SCOPE_STORE |
| 47 | + )) { |
| 48 | + $cssMatches = []; |
| 49 | + // add link rel preload to style sheets |
| 50 | + $content = preg_replace_callback( |
| 51 | + '@<link\b.*?rel=("|\')stylesheet\1.*?/>@', |
| 52 | + function ($matches) use (&$cssMatches) { |
| 53 | + $cssMatches[] = $matches[0]; |
| 54 | + preg_match('@href=("|\')(.*?)\1@', $matches[0], $hrefAttribute); |
| 55 | + $href = $hrefAttribute[2]; |
| 56 | + if (preg_match('@media=("|\')(.*?)\1@', $matches[0], $mediaAttribute)) { |
| 57 | + $media = $mediaAttribute[2]; |
| 58 | + } |
| 59 | + $media = $media ?? 'all'; |
| 60 | + $loadCssAsync = sprintf( |
| 61 | + '<link rel="preload" as="style" media="%s" . |
| 62 | + onload="this.onload=null;this.rel=\'stylesheet\'"' . |
| 63 | + 'href="%s">', |
| 64 | + $media, |
| 65 | + $href |
| 66 | + ); |
| 67 | + |
| 68 | + return $loadCssAsync; |
| 69 | + }, |
| 70 | + $content |
| 71 | + ); |
| 72 | + |
| 73 | + if (!empty($cssMatches)) { |
| 74 | + $content = str_replace('</body', implode("\n", $cssMatches) . "\n</body", $content); |
| 75 | + $subject->setContent($content); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments