jsMinifier = $jsMinifier; /** * @TODO Refactor when leave support of Magento 2.3.7 and less */ $this->secureHtmlRenderer = class_exists(SecureHtmlRenderer::class) ? $objectManager->get(SecureHtmlRenderer::class) : null; } protected function _toHtml() { $html = parent::_toHtml(); preg_match_all('//', $html, $scriptTags); $scriptTags = array_shift($scriptTags); foreach ($scriptTags as $scriptTag) { try { $modifiedScriptTag = $this->modifyScriptTag($scriptTag); } catch (\Exception $e) { continue; } $html = str_replace($scriptTag, $modifiedScriptTag, $html); } return $html; } /** * Modify script tag to prevent from being moved to footer * * @param string $scriptTag * @return string * @throws \Exception */ private function modifyScriptTag(string $scriptTag): string { /** * @TODO Refactor when leave support of Magento 2.3.7 and less */ if (! $this->secureHtmlRenderer) { preg_match('#([^`]*?)<\/script>#', $scriptTag, $matches); if(isset($matches[1])) { $originalTagContent = $matches[1]; $minifiedContent = $this->jsMinifier->minify($originalTagContent); $scriptTag = str_replace($originalTagContent, $minifiedContent, $scriptTag); } return str_replace( [''], ['<' . self::SCRIPT_TAG_REPLACEMENT, '/'.self::SCRIPT_TAG_REPLACEMENT.'>'], $scriptTag ); } $doc = new \DOMDocument(); $doc->loadHTML($scriptTag); $scriptNode = $doc->getElementsByTagName('script')->item(0); $tagAttributes = array_column(iterator_to_array($scriptNode->attributes), 'nodeValue', 'name'); $tagContent = $this->jsMinifier->minify($scriptNode->textContent); return $this->secureHtmlRenderer->renderTag(self::SCRIPT_TAG_REPLACEMENT, $tagAttributes, $tagContent, false); } }