Created
December 13, 2018 05:12
-
-
Save kyrare/c1f8609d1fba4bd350f5a99b0b6bfdab to your computer and use it in GitHub Desktop.
Add links preload for bitrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
\Bitrix\Main\EventManager::getInstance()->addEventHandler('main', 'OnEndBufferContent', 'addLinksPreload'); | |
function addLinksPreload(&$content) | |
{ | |
global $USER, $APPLICATION; | |
if ((is_object($USER) && $USER->IsAuthorized()) || strpos($APPLICATION->GetCurDir(), '/bitrix/') !== false) return; | |
$arAdd = []; | |
$arMatches = []; | |
preg_match_all('/<link.+?href="(.+?\.css\?\d+)"[^>]*>/', $content, $arMatches); | |
if (!empty($arMatches[1])) { | |
foreach ($arMatches[1] as $sSrc) { | |
$arAdd[] = '<link href="' . $sSrc . '" rel="preload" as="style">'; | |
} | |
} | |
preg_match_all('/<script.+?src="(.+?\.js\?\d+)"[^>]*><\/script\>/', $content, $arMatches); | |
if (!empty($arMatches[1])) { | |
foreach ($arMatches[1] as $sSrc) { | |
$arAdd[] = '<link href="' . $sSrc . '" rel="preload" as="script">'; | |
} | |
} | |
if ($arAdd) { | |
$content = preg_replace('/<\/title>/', '</title>' . PHP_EOL . implode(PHP_EOL, $arAdd), $content, 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment