To load a YouTube video using data-src instead of an iframe, you can lazy load the video to improve performance, especially when dealing with multiple videos on a page. Here’s how you can do it:
HTML Structure
You can create a div with a data-src attribute that holds the YouTube video URL. Initially, the video iframe will be replaced with an image (thumbnail) or a placeholder. When the user interacts with the element (e.g., clicks on it), the actual iframe is loaded.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<div class="youtube-video" data-src="https://youtu.be/hzboPlVtaMg"> <div class="play-button"></div> <img src="https://img.youtube.com/vi/YOUR_VIDEO_ID/0.jpg" alt="YouTube Video Thumbnail"> </div> .youtube-video { position: relative; width: 100%; max-width: 560px; cursor: pointer; } .youtube-video img { width: 100%; height: auto; } .youtube-video .play-button { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 68px; height: 48px; background: url('https://i.imgur.com/TxzC70f.png') no-repeat center center; background-size: cover; pointer-events: none; } Use JavaScript to replace the placeholder with the actual iframe when the user clicks on the thumbnail. document.addEventListener('DOMContentLoaded', function() { var videos = document.querySelectorAll('.youtube-video'); videos.forEach(function(video) { video.addEventListener('click', function() { var iframe = document.createElement('iframe'); iframe.setAttribute('src', video.getAttribute('data-src') + '?autoplay=1'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowfullscreen', '1'); iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture'); video.innerHTML = ''; // Clear the content video.appendChild(iframe); // Insert the iframe }); }); }); |