Vừa mình làm xong dự án, trong web cần chèn mấy iframe (Như google maps, tỷ giá các bên, youtube…) vào web nên khi load khá bất tiện và gây nặng web. Các plugin cache đã hỗ trợ sẵn việc lazy load iframe nhưng đôi khi dự án đó không dùng tới các plugin cache đó hoặc không muốn cài thêm plugin ngoài hỗ trợ việc đó

Ý tưởng như sau: Chuyển src thành data-src. sau khi kéo chuột tới vùng chứa iframe thì mới thay lại src để load iframe. Vậy nên mình đã nhờ chatgpt và theo ý tưởng của mình để viết đoạn code hoàn chỉnh giúp Lazy load iframe để tăng tốc tải trang.
Kết quả: Đã test và hoạt động tốt
Để duy trì blog nên mình có làm aff cho 1 số bên hosting. Nhưng dù aff mình cũng chọn 1 số nhà cung cấp uy tín về chất lượng và support nên các bạn cứ yên tâm nhé.
Nếu có mua hosting mà có trong list dưới đây các bạn click vào link trước khi mua để ủng hộ mình nhé. Mình cảm ơn nhiều
- Azdigi: Giá rẻ thì dùng gói Pro Gold Hosting còn chất lượng hơn thì em khuyên dùng Business Hosting. Có điều kiện thì lên VPS nhé
- Tino hosting
- iNet
- Nước ngoài thì Vultr
Cách để lazy load iframe
Bạn chỉ cần chèn đoạn code sau vào file functions.php trong wp-content/themes/[theme của bạn]/functions.php là được nhé
/*
* Lazy load Iframe
* levantoan.com
* */
add_filter('the_content', 'devvn_lazyload_iframe_src');
add_filter('widget_text', 'devvn_lazyload_iframe_src');
add_filter('widget_text_content', 'devvn_lazyload_iframe_src');
add_filter('widget_custom_html_content', 'devvn_lazyload_iframe_src');
function devvn_lazyload_iframe_src($content) {
// Match tất cả iframe có thuộc tính src
$pattern = '/<iframe([^>]+?)src=["\']([^"\']+)["\'](.*?)>/i';
$replacement = '<iframe$1data-src="$2"$3 loading="lazy"></iframe>';
return preg_replace($pattern, $replacement, $content);
}
add_action('wp_footer', function (){
?>
<script>
document.addEventListener("DOMContentLoaded", function () {
const iframes = document.querySelectorAll("iframe[data-src]");
function loadIframe(iframe) {
const src = iframe.getAttribute("data-src");
if (src) {
iframe.setAttribute("src", src);
iframe.removeAttribute("data-src");
}
}
if ("IntersectionObserver" in window) {
// Trình duyệt hiện đại dùng IntersectionObserver
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
loadIframe(entry.target);
observer.unobserve(entry.target);
}
});
});
iframes.forEach(iframe => observer.observe(iframe));
} else {
// Trình duyệt cũ: fallback bằng scroll
function isInViewport(el) {
const rect = el.getBoundingClientRect();
const preloadOffset = 100;
return (
rect.top <= window.innerHeight + preloadOffset &&
rect.bottom >= 0
);
}
function checkAndLoadIframes() {
iframes.forEach(iframe => {
if (iframe.getAttribute("data-src") && isInViewport(iframe)) {
loadIframe(iframe);
}
});
}
// Gọi 1 lần lúc DOM loaded
checkAndLoadIframes();
// Gọi khi scroll
window.addEventListener('scroll', checkAndLoadIframes);
window.addEventListener('resize', checkAndLoadIframes);
}
});
</script>
<?php
}, 999);
Nếu bạn có ý tưởng nào hay hơn hãy comment nhé
- Bình luận