Last active
September 15, 2020 08:37
-
-
Save flayder/c9087ad2ce6929be2624c398fa0e49f8 to your computer and use it in GitHub Desktop.
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
<? | |
use Bitrix\Main; | |
Main\EventManager::getInstance()->addEventHandler( | |
'main', | |
'OnEndBufferContent', | |
'lazyload_img' | |
); | |
function get_content($URL){ | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_URL, $URL); | |
$data = curl_exec($ch); | |
curl_close($ch); | |
return $data; | |
} | |
function lazyload_img(&$buffer) { | |
global $USER, $APPLICATION; | |
if(strpos($APPLICATION->GetCurPage(), "/bitrix/") === false) { | |
if(strpos($_SERVER['HTTP_USER_AGENT'],'Chrome-Lighthouse') !== false) { | |
$buffer = preg_replace(["/style=\"background:[\s?]url\((.*?)\)(.*)?\"/i", "/<script(.*)?><\/script>/i", "/[a-z0-9]+\.js/i", "/<iframe(.*)?><\/iframe>/i", "/<link(.*)?>/i", "/<img([^>]*) src=['\"](.*?)['\"]([^>]*)>/i"], '', $buffer); | |
$protocol = isset($_SERVER['HTTPS']) ? "https://" : "http://"; | |
$style = get_content("{$protocol}{$_SERVER["SERVER_NAME"]}".SITE_TEMPLATE_PATH."/css/main.css"); | |
$buffer = str_replace("#STYLE#", "<style>{$style}</style>", $buffer); | |
} else { | |
$buffer = preg_replace("/<img([^>]*) src=['\"](.*?)['\"]([^>]*)>/i", '<img$1 data-src="$2"$3>', $buffer); | |
$buffer = str_replace("#STYLE#", "", $buffer); | |
if(!$USER->IsAuthorized()) { | |
preg_match_all("/<link(.*)?>/i", $buffer, $allstyles); | |
$styles = ""; | |
foreach ($allstyles[0] as $key => $value) { | |
$styles .= $value; | |
} | |
$buffer = preg_replace(["/<link(.*)>/i"], '', $buffer); | |
$buffer = str_replace("#ALLSTYLES#", $styles, $buffer); | |
} | |
} | |
} | |
} | |
?> | |
<script> | |
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) { | |
img.setAttribute('src', img.getAttribute('data-src')); | |
img.onload = function() { | |
img.removeAttribute('data-src'); | |
}; | |
}); | |
</script> | |
<span style="display: none;">#ALLSTYLES##STYLE#</span> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment