Created
January 24, 2022 09:52
-
-
Save ihorduchenko/b21c3ce6b113c34b41773cf35903d1d7 to your computer and use it in GitHub Desktop.
Lazy-load YouTube videos on click
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="lazyVideoLoader"> | |
<a href="javascript:;" data-video-id="VIDEO_ID" class="feature-row__video-trigger lazyVideoTrigger"> | |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80"> | |
<path d="M40 0a40 40 0 1040 40A40 40 0 0040 0zM26 61.56V18.44L64 40z"></path> | |
</svg> | |
</a> | |
</div> | |
<script> | |
var lazyVideoLoader = document.querySelectorAll('.lazyVideoLoader'); | |
lazyVideoLoader.forEach(function(el) { | |
let lazyVideoTrigger = el.querySelector('.lazyVideoTrigger'); | |
lazyVideoTrigger.addEventListener('click', function(e) { | |
let videoID = e.target.getAttribute('data-video-id'); | |
let iFrame = document.createElement('iframe'); | |
iFrame.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture'); | |
iFrame.src = 'https://www.youtube.com/embed/' + videoID + '?autoplay=1'; | |
el.appendChild(iFrame); | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment