|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace React\React; |
| 4 | + |
| 5 | +use Magento\Framework\App\Config\ScopeConfigInterface as Config; |
| 6 | +use Magento\Framework\Event\ObserverInterface; |
| 7 | + |
| 8 | +class DeferCSS implements ObserverInterface |
| 9 | +{ |
| 10 | + public function __construct( |
| 11 | + protected Config $config |
| 12 | + ) { |
| 13 | + } |
| 14 | + |
| 15 | + public function execute(\Magento\Framework\Event\Observer $observer) |
| 16 | + { |
| 17 | + // Check if defer CSS is enabled (config or GET parameter) |
| 18 | + if (!$this->shouldDeferCSS()) { |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + $response = $observer->getEvent()->getData('response'); |
| 23 | + if (!$response) { |
| 24 | + return; |
| 25 | + } |
| 26 | + $html = $response->getBody(); |
| 27 | + if ($html == '') { |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + $html = $this->deferCSS($html); |
| 32 | + $response->setBody($html); |
| 33 | + } |
| 34 | + |
| 35 | + private function shouldDeferCSS(): bool |
| 36 | + { |
| 37 | + // Check GET parameter first |
| 38 | + if (isset($_GET['defer-css']) && $_GET['defer-css'] === "false") { |
| 39 | + return false; |
| 40 | + } |
| 41 | + if (isset($_GET['defer-css']) && $_GET['defer-css'] === "true") { |
| 42 | + return true; |
| 43 | + } |
| 44 | + |
| 45 | + // Fall back to config (default to true if not set) |
| 46 | + $configValue = $this->config->getValue('react_vue_config/css/defer_css'); |
| 47 | + return $configValue === null || $configValue === '' ? true : boolval($configValue); |
| 48 | + } |
| 49 | + |
| 50 | + private function deferCSS(string $html): string |
| 51 | + { |
| 52 | + // Match link tags with styles-l.css (handles both /> and > closing, with or without whitespace) |
| 53 | + $stylesLPattern = '@<link[^>]*href=["\'][^"\']*styles-l[^"\']*\.css[^"\']*["\'][^>]*\s*/?>@i'; |
| 54 | + |
| 55 | + $scriptsToInsert = []; |
| 56 | + |
| 57 | + if (preg_match_all($stylesLPattern, $html, $allMatches, PREG_OFFSET_CAPTURE)) { |
| 58 | + // Process matches in reverse order to maintain correct offsets when replacing |
| 59 | + $matches = array_reverse($allMatches[0]); |
| 60 | + |
| 61 | + foreach ($matches as $match) { |
| 62 | + $stylesLTag = $match[0]; |
| 63 | + |
| 64 | + // Check if stylesheet has desktop-only media query (safe to defer on mobile) |
| 65 | + if (!$this->hasDesktopMediaQuery($stylesLTag)) { |
| 66 | + continue; |
| 67 | + } |
| 68 | + |
| 69 | + $href = $this->extractHref($stylesLTag); |
| 70 | + $media = $this->extractMedia($stylesLTag); |
| 71 | + |
| 72 | + // Build preload link for desktop (in HTML source) |
| 73 | + $preloadLink = '<link rel="preload" as="style" fetchpriority="high" href="' . htmlspecialchars($href, ENT_QUOTES) . '"' . ($media ? ' media="' . htmlspecialchars($media, ENT_QUOTES) . '"' : '') . '>'; |
| 74 | + |
| 75 | + // Build the deferred script |
| 76 | + // Desktop: uses document.write() for blocking synchronous load before FCP |
| 77 | + // Mobile: uses setTimeout with createElement for async delayed load |
| 78 | + $deferredScript = '<script no-defer> |
| 79 | + (function () { |
| 80 | + var isDesktop = window.matchMedia("(min-width: 768px)").matches; |
| 81 | +
|
| 82 | + if (isDesktop) { |
| 83 | + // Acts as if the <link> was in original HTML → BLOCKS before FCP |
| 84 | + document.write( |
| 85 | + \'<link rel="stylesheet" href="' . htmlspecialchars($href, ENT_QUOTES) . '"' . ($media ? ' media="' . htmlspecialchars($media, ENT_QUOTES) . '"' : '') . '>\' |
| 86 | + ); |
| 87 | + } else { |
| 88 | + // Mobile: delayed, non-blocking |
| 89 | + setTimeout(function () { |
| 90 | + var l = document.createElement("link"); |
| 91 | + l.rel = "stylesheet"; |
| 92 | + l.href = "' . htmlspecialchars($href, ENT_QUOTES) . '"; |
| 93 | + ' . ($media ? 'l.media = "' . htmlspecialchars($media, ENT_QUOTES) . '";' : '') . ' |
| 94 | + document.head.appendChild(l); |
| 95 | + }, 0); |
| 96 | + } |
| 97 | + })(); |
| 98 | +</script>'; |
| 99 | + |
| 100 | + // Remove original link tag |
| 101 | + $html = str_replace($stylesLTag, '', $html); |
| 102 | + |
| 103 | + // Collect preload link and script to insert after mobile styles |
| 104 | + $scriptsToInsert[] = $preloadLink . $deferredScript; |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + // Insert scripts after mobile styles (styles-m.css, category-styles-m.min.css, etc.) |
| 109 | + // but before desktop styles |
| 110 | + if (!empty($scriptsToInsert) && preg_match('/<head[^>]*>/i', $html, $headMatch, PREG_OFFSET_CAPTURE)) { |
| 111 | + $headPos = $headMatch[0][1] + strlen($headMatch[0][0]); |
| 112 | + $headContent = substr($html, $headPos); |
| 113 | + |
| 114 | + // Find the last mobile stylesheet (styles-m.css or category-styles-m.min.css, etc.) |
| 115 | + // Pattern: link tags with styles-m or category-styles-m or product-styles-m, etc. |
| 116 | + $mobileStylesPattern = '@<link[^>]*href=["\'][^"\']*(?:styles-m|category-styles-m|product-styles-m|home-styles-m)[^"\']*\.css[^"\']*["\'][^>]*\s*/?>@i'; |
| 117 | + |
| 118 | + $insertPosition = 0; |
| 119 | + if (preg_match_all($mobileStylesPattern, $headContent, $mobileMatches, PREG_OFFSET_CAPTURE)) { |
| 120 | + // Find the position after the last mobile stylesheet |
| 121 | + $lastMobileMatch = end($mobileMatches[0]); |
| 122 | + $insertPosition = $lastMobileMatch[1] + strlen($lastMobileMatch[0]); |
| 123 | + } |
| 124 | + |
| 125 | + // Insert scripts after mobile styles (or at beginning of head if no mobile styles found) |
| 126 | + $beforeScripts = substr($headContent, 0, $insertPosition); |
| 127 | + $afterScripts = substr($headContent, $insertPosition); |
| 128 | + |
| 129 | + $html = substr($html, 0, $headPos) . $beforeScripts . implode('', $scriptsToInsert) . $afterScripts; |
| 130 | + } |
| 131 | + |
| 132 | + return $html; |
| 133 | + } |
| 134 | + |
| 135 | + private function hasDesktopMediaQuery(string $linkTag): bool |
| 136 | + { |
| 137 | + if (preg_match('/media=["\']([^"\']+)["\']/i', $linkTag, $matches)) { |
| 138 | + $media = $matches[1]; |
| 139 | + // Check if media query contains min-width (desktop-only) |
| 140 | + return preg_match('/min-width\s*:\s*(\d+)/i', $media) === 1; |
| 141 | + } |
| 142 | + return false; |
| 143 | + } |
| 144 | + |
| 145 | + private function extractMedia(string $linkTag): string |
| 146 | + { |
| 147 | + if (preg_match('/media=["\']([^"\']+)["\']/i', $linkTag, $matches)) { |
| 148 | + return $matches[1]; |
| 149 | + } |
| 150 | + return ''; |
| 151 | + } |
| 152 | + |
| 153 | + private function extractHref(string $linkTag): string |
| 154 | + { |
| 155 | + if (preg_match('/href=["\']([^"\']+)["\']/i', $linkTag, $matches)) { |
| 156 | + return $matches[1]; |
| 157 | + } |
| 158 | + return ''; |
| 159 | + } |
| 160 | +} |
0 commit comments