Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active April 7, 2022 21:58
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sabrina-zeidan/332d35138be8bf668f0d20c23150e7f7 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/332d35138be8bf668f0d20c23150e7f7 to your computer and use it in GitHub Desktop.
YouTube lazy load JavaScript
/* Light YouTube Embeds by @labnol */
/* Web: http://labnol.org/?p=27941 */
document.addEventListener("DOMContentLoaded",
function() {
var div, n,
v = document.getElementsByClassName("youtube-player");
for (n = 0; n < v.length; n++) {
div = document.createElement("div");
div.setAttribute("data-id", v[n].dataset.id);
div.innerHTML = labnolThumb(v[n].dataset.id);
div.onclick = labnolIframe;
v[n].appendChild(div);
}
});
function labnolThumb(id) {
var thumb = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg">',
play = '<div class="play"></div>';
return thumb.replace("ID", id) + play;
}
function labnolIframe() {
var iframe = document.createElement("iframe");
var embed = "https://www.youtube.com/embed/ID?autoplay=1";
iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment