Code lazy load YouTube videos trong WordPress không cần plugin

Khi nhúng video YouTube vào WordPress, mặc định hệ thống sẽ tải toàn bộ iframe embed cùng với các script của YouTube ngay từ đầu. Điều này làm tăng đáng kể kích thước trang và giảm tốc độ load, đặc biệt khi có nhiều video.

Vấn đề hiệu suất khi nhúng video Youtube vào WordPress

  • Mỗi video YouTube nhúng thêm khoảng 1.1 MB dữ liệu
  • Trang có 1 video: ~1315 KB
  • Trang có 10 video: ~12 MB (!!)
  • PageSpeed score giảm xuống 45-90 điểm và tốc độ tải trang thực tế cũng giảm

Giải Pháp khắc phục là dùng code Lazy Load

Code snippet dưới đây sẽ giúp bạn:

✅ Chỉ load thumbnail nhẹ (~50-100 KB) khi trang load
✅ Load iframe thực chỉ khi user click vào video
✅ Tăng PageSpeed lên 100 điểm
✅ Giảm kích thước trang 9-44 lần
✅ Sử dụng YouTube no-cookie domain (youtube-nocookie.com)
✅ Không cần WP_HTTP API request
✅ Không cần clear oEmbed cache

Code Lazy Load Video Youtube

Thêm code sau vào file functions.php của theme, bạn có thể xem qua


<?php
/**
 * Lazy Load YouTube Videos - WordPress Code Snippet
 * Version: 1.0
 * Description: Tối ưu tốc độ load trang bằng cách lazy load YouTube embeds
 */

/* Convert single line YouTube URL to lazy embeds */
add_filter('the_content', 'vutruso_yt_lazy_embed', 6); 

function vutruso_yt_lazy_embed($content) { 
    // Tùy chọn wrapper cho iframe
    // Option 1: Không wrapper
    // $yt_wrap = '';
    
    // Option 2: Sử dụng wrapper có sẵn của theme
    // $yt_wrap = '<div class="nv-iframe-embed my3">{content}</div>';
    
    // Option 3: Wrapper tích hợp CSS responsive (khuyến nghị)
    $yt_wrap = '<div><div class="vutruso_yt_lazy_embed">{content}</div></div><style>.vutruso_yt_lazy_embed{position:relative;padding-bottom:56.25%;height:0;margin:1rem 0;} .vutruso_yt_lazy_embed iframe{position:absolute;top:0;left:0;width:100%;height:100%;}</style>';

    // Kiểm tra có URL YouTube trong content không
    if (strpos($content, 'youtube.com') !== false || strpos($content, 'youtu.be') !== false) {
        $startpreg = microtime(true);

        /*
         * Hỗ trợ các định dạng URL YouTube:
         * - https://www.youtube.com/watch?v=VIDEO_ID
         * - https://youtu.be/VIDEO_ID
         * - https://www.youtube.com/embed/VIDEO_ID
         * - https://youtu.be/VIDEO_ID?t=123
         */
        $yt_regex = '$(?:\n)(?:https?:\/\/)?(?:www\.)?youtu(?:\.be\/|be\.com\/\S*(?:watch|embed)(?:(?:(?=\/[-a-zA-Z0-9_]{11,}(?!\S))\/)|(?:\S*v=|v\/)))([-a-zA-Z0-9_]{11,})(?:[^\r\n]*)$i';
        $yt_var = '$1';

        // Cấu hình embed URL với no-cookie domain
        $embed_url = 'https://www.youtube-nocookie.com/embed/' . $yt_var . '?feature=oembed&playsinline=1&rel=0';
        $thumb_url = 'https://img.youtube.com/vi/' . $yt_var . '/hqdefault.jpg';
        
        // SVG icon YouTube play button
        $yt_svg = '<svg xmlns="http://www.w3.org/2000/svg" style="pointer-events:none;display:block;width:100%;height:100%" viewBox="0 0 28.6 20"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 28.6 20"><path fill="red" d="M28 3.1A3.6 3.6 0 0 0 25.4.6C23.2 0 14.3 0 14.3 0S5.3 0 3 .6A3.6 3.6 0 0 0 .6 3.1 37.2 37.2 0 0 0 .6 17a3.6 3.6 0 0 0 2.5 2.5c2.3.6 11.2.6 11.2.6s9 0 11.1-.6a3.6 3.6 0 0 0 2.6-2.5c.6-2.3.6-6.9.6-6.9s0-4.6-.6-6.9Z"/><path fill="#fff" d="m11.4 14.3 7.4-4.3-7.4-4.3v8.6Z"/></svg></svg>';
        
        // HTML cho thumbnail với play button (sử dụng srcdoc)
        $yt_srcdoc = htmlentities('<style>* { overflow: hidden; padding: 0; margin: 0;}html,body { height: 100%;}a { position: absolute; z-index: 9999; inset: 0; background-color:whitesmoke;}a img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: center;transition:0.3s;} a:hover img{filter: brightness(70%);} span { position: absolute; z-index: 1; inset: 50%; width:84px; height:84px; max-width:20%; transform: translate(-50%, -50%); opacity:0.8; transition:0.3s;}span svg {display: block;} a:hover span{opacity:1;}</style><a href="' . $embed_url . '"><span>' . $yt_svg . '</span><img loading="lazy" src="' . $thumb_url . '"></a>');
        
        // Tạo iframe với lazy loading
        $yt_replace = '<iframe loading="lazy" srcdoc="' . $yt_srcdoc . '" title="video" width="1200" height="900" src="' . htmlentities($embed_url) . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="allowfullscreen"></iframe>';

        if (!empty($yt_wrap)) {
            $yt_replace = str_replace('{content}', $yt_replace, $yt_wrap);
        } 

        // Convert YouTube URLs thành lazy iframe embeds
        $content = trim(preg_replace($yt_regex, $yt_replace, "\n" . $content . " ")) . ' <!-- [vutruso_yt_lazy_embed:' . round((microtime(true) - $startpreg) / 1000) . 'ms] -->'; 
    }

    return $content;
}

/* Đăng ký internal oEmbed provider - không cache, không style theme */
add_action('init', 'vutruso_yt_register_oembed_provider');

function vutruso_yt_register_oembed_provider() {
    wp_embed_register_handler(
        'vutruso_yt',
        '$(?:https?:\/\/)?(?:www\.)?youtu(?:\.be\/|be\.com\/\S*(?:watch|embed)(?:(?:(?=\/[-a-zA-Z0-9_]{11,}(?!\S))\/)|(?:\S*v=|v\/)))([-a-zA-Z0-9_]{11,})$i',
        'vutruso_yt_callback_oembed_provider'
    );
}

function vutruso_yt_callback_oembed_provider($matches) {
    return vutruso_yt_lazy_embed($matches[0]) . '<!-- [vutruso_yt_callback_oembed_provider] -->';
}

/* Bảo vệ URL trong thẻ <pre> khỏi bị convert */
add_filter('the_content', 'vutruso_yt_preserve_pre', 5); 
add_filter('the_content', 'vutruso_yt_preserve_pre_clean', 99999);

function vutruso_yt_preserve_pre($content) {
    // Sửa đổi URL YouTube trong <pre> để không bị embed
    $pre_regex = '/<pre[^>]*>(.*?)<\/pre>/s';
    $arr_pre = array(); 
    $placeholder = '<!-- preserve this youtube url -->';
    $arr_replace = array(
        'youtube.com' => $placeholder . 'you' . $placeholder . 'tub' . $placeholder . 'e.c' . $placeholder . 'om',
        'youtu.be' => $placeholder . 'you' . $placeholder . 'tu.b' . $placeholder . 'e'
    );

    if (strpos($content, '<pre') !== false && preg_match_all($pre_regex, $content, $matches)) {
        foreach ($matches[0] as $index => $pre) { 
            $pre_prevented = str_replace(array_keys($arr_replace), array_values($arr_replace), $pre); 
            $arr_pre[$pre_prevented] = $pre;
        }
        $content = str_replace(array_values($arr_pre), array_keys($arr_pre), $content);
    }

    return $content;
}

function vutruso_yt_preserve_pre_clean($content) {
    $placeholder = '<!-- preserve this youtube url -->';
    if (strpos($content, $placeholder) !== false) {
        $content = str_replace($placeholder, '', $content);
    }
    return $content;
}

Cách thêm code vào functions.php

Cách 1: Thêm vào functions.php

  1. Vào Appearance → Theme File Editor
  2. Chọn file functions.php
  3. Paste code vào cuối file
  4. Click Update File

Cách 2: Tạo Custom Plugin

  1. Tạo folder mới: wp-content/plugins/lazy-youtube/
  2. Tạo file lazy-youtube.php với nội dung:
<?php
/**
 * Plugin Name: Lazy Load YouTube Videos
 * Description: Tối ưu tốc độ bằng lazy loading YouTube embeds
 * Version: 1.0
 * Author: Your Name
 */

// Paste toàn bộ code bên trên vào đây
  1. Kích hoạt plugin trong Plugins → Installed Plugins

Cách Nhúng Video vào WordPress

Sau khi cài đặt, bạn chỉ cần paste URL YouTube vào:

Classic Editor:

Paste URL riêng một dòng



https://www.youtube.com/watch?v=VIDEO_ID

Block Editor (Gutenberg):

  • Tạo paragraph mới
  • Paste URL YouTube
  • WordPress tự động convert

Widget:

  • Hỗ trợ cả Classic Widget và Block Widget
  • Paste URL vào text widget hoặc embed block

Kết Quả Thực Tế

So Sánh PageSpeed Score

Trường hợp PageSpeed Score Kích thước Cải thiện
1 video (thường) 45-90 1,315 KB
1 video (lazy) 100 145 KB 9x nhẹ hơn
10 videos (thường) 57 12,338 KB
10 videos (lazy) 100 278 KB 44x nhẹ hơn

Lợi Ích Cụ Thể

🚀 Tốc độ: PageSpeed score đạt tăng đáng kể
💾 Băng thông: Tiết kiệm 9-44 lần dung lượng
📱 Mobile: Cực kỳ quan trọng cho người dùng di động
🔒 Bảo mật: Sử dụng youtube-nocookie.com
Server: Không gọi API, không cache oEmbed

Tương Thích

Editors: Classic Editor, Block Editor (Gutenberg)
Widgets: Classic Widgets, Block Widgets
Themes: Classic themes (Neve, Sparkling…), FSE themes (Twenty Twenty-Three, Four…)
WordPress: 5.0+, PHP 7.4+

Tùy Chỉnh

Thay đổi wrapper CSS

Trong hàm vutruso_yt_lazy_embed(), sửa biến $yt_wrap:

// Không wrapper (không khuyến nghị)
$yt_wrap = '';

// Dùng class của theme
$yt_wrap = '<div class="your-theme-video-wrapper">{content}</div>';

// Custom CSS
$yt_wrap = '<div class="custom-video"><div class="ratio-16-9">{content}</div></div>';

Thêm tham số embed

Sửa biến $embed_url để thêm tham số:

// Thêm autoplay, mute
$embed_url = 'https://www.youtube-nocookie.com/embed/' . $yt_var . '?autoplay=1&mute=1&rel=0';

// Ẩn controls
$embed_url = 'https://www.youtube-nocookie.com/embed/' . $yt_var . '?controls=0&rel=0';

Kết Luận

Code snippet này là giải pháp hoàn hảo để tối ưu YouTube embeds trong WordPress mà không cần plugin. Với kết quả PageSpeed 100/100 và giảm 9-44 lần kích thước trang, đây là must-have optimization cho mọi website WordPress có video.

Lưu ý quan trọng: Luôn backup website trước khi thêm code mới vào functions.php

Nguồn tham khảo: Lazy load YouTube video iframe inspired by in 2024.

5/5 - (361 votes)

vutruso

Vũ Trụ Số chuyên cung cấp hosting cho WordPress, dịch vụ thiết kế website, quản trị website cho doanh nghiệp, các dịch vụ bảo mật website WordPress, tăng tốc website WordPress