Answer the question
In order to leave comments, you need to log in
Trying to speed up page loading in BX, what do you say?
Hello! In an attempt to achieve maximum site loading speed, I go through various practices and try to apply them in my projects.
Now my interest fell on the delayed loading of scripts, which can be seen on the Lamoda website, in general, there are many interesting solutions that allow you to load the page with incredible speed. For example, pictures are compressed in webp. But now I'm interested in lazy loading of scripts. In fact, it will not be difficult to implement this mechanism, it is enough to use a couple of lines of JS:
var script = document.createElement('script');
script.src = src;
document.body.appendChild(script);
// Вешаем обработчик события и получаем код страницы
$eventManager->addEventHandler("main", "OnEndBufferContent", "deferredLoading");
// Наш обработчик
function deferredLoading(&$content){
// Паттерн который будет отделять названия файла
$getPattern = '/src=".*.js.*"/';
// Список паттернов по которым будем искать нужные нам скрипты, в данном примере ищем core_db.js и loadext.js
$arScripts = [
["del" => '/<script.+?src=".+?bitrix\/js\/main\/core\/core_db[^"]+"><\/script\>/'],
["del" => '/<script.+?src=".+?bitrix\/js\/main\/loadext\/loadext[^"]+"><\/script\>/']
];
// Ищем и находим
foreach ($arScripts as &$script){
preg_match($script["del"], $content, $res);
if($res[0]) {
preg_match($getPattern, $res[0], $res);
$res = str_replace("src=", "", $res);
$content = preg_replace($script["del"], "", $content);
$script["script"] = $res[0];
}
}
unset($script);
// Добавляем найденные скрипты
$strScr = '';
for($i = 0; $i < count($arScripts); $i++) {
$strScr .= ($i < count($arScripts)-1) ? "".$arScripts[$i]['script'].",\n " : "".$arScripts[$i]['script']."";
}
// JS Скрипт, который будет подключать все это дело
$string = "
<script>
function fastLoad() {
var scripts = [
$strScr
];
load = function (src) {
var script = document.createElement('script');
script.src = src;
document.body.appendChild(script);
};
for (var i = 0; i < scripts.length; i++) {
load(scripts[i]);
}
}
fastLoad();
</script>";
// Ставим в нужном месте в шаблоне тег, вместо которого вставится наш JS код
$content = str_replace("<!-- add_js -->",$string, $content);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question