Skip to content

Instantly share code, notes, and snippets.

@kyrare
Created December 13, 2018 05:12
Show Gist options
  • Save kyrare/c1f8609d1fba4bd350f5a99b0b6bfdab to your computer and use it in GitHub Desktop.
Save kyrare/c1f8609d1fba4bd350f5a99b0b6bfdab to your computer and use it in GitHub Desktop.
Add links preload for bitrix
<?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