Skip to content

Instantly share code, notes, and snippets.

@determin1st
Created September 21, 2019 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save determin1st/7042182e40239b4be1e80b4e8d185d1c to your computer and use it in GitHub Desktop.
Save determin1st/7042182e40239b4be1e80b4e8d185d1c to your computer and use it in GitHub Desktop.
ленивая загрузка <iframe> для темы WordPress
# фильтр для ленивой загрузки <iframe>
add_filter('embed_oembed_html', function($html) {
# проверим что это iframe
if (stripos($html, '<iframe') === false) {
return $html;
}
# проверим наличие источника
if (($a = strpos($html, ' src=')) === false) {
return $html;
}
# преобразуем источник в пассивный атрибут данных
$html = substr($html, 0, $a).' data-src='.substr($html, $a + 5);
# добавим атрибут loading=lazy (для новых браузеров)
if (strpos($html, ' loading=') === false)
{
$a = strpos($html, '>');
$html = substr($html, 0, $a).' loading="lazy"'.substr($html, $a);
}
return $html;
});
loadIFrames = function(){
var list;
list = [...(document.querySelectorAll('iframe'))];
list.forEach(function(iframe){
if ('src' in iframe.dataset) {
iframe.src = iframe.dataset.src;
}
});
};
window.addEventListener('load', function(){
loadIFrames();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment