-
-
Save sabrina-zeidan/332d35138be8bf668f0d20c23150e7f7 to your computer and use it in GitHub Desktop.
YouTube lazy load JavaScript
This file contains 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
/* 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