Skip to content

Instantly share code, notes, and snippets.

@do18
Last active July 13, 2023 11:22
Show Gist options
  • Save do18/09761dfabf60689b2cd8 to your computer and use it in GitHub Desktop.
Save do18/09761dfabf60689b2cd8 to your computer and use it in GitHub Desktop.
If you are concerned about web site performance, you probably noticed that embedded YouTube iframes are costly. Instead of iframes, you may embed images that link to the respective videos, and make these links replace themselves with iframes when clicked. (IE 9+ because of getElementsByClassName.)
/*jshint maxlen: 79 */
var MYSITE = MYSITE || {};
/**
* Make YouTube links with .yt-embed replace themselves with YouTube iframes
* when clicked. The first child element is assumed to be the img element
* holding the poster frame. The YouTube URL must contain the "v" parameter,
* but no further parameters. The data-yt-options attribute may hold iframe
* URL parameters.
*
* @param {Document} d The window.document object.
*/
MYSITE.yt_embed = function (d) {
'use strict';
var el;
var els = d.getElementsByClassName('yt-embed');
var i;
var max;
var replace_with_iframe = function (e) {
var iframe = d.createElement('iframe');
var video_id = e.currentTarget.href.split('=')[1];
var options = e.currentTarget.getAttribute('data-yt-options');
iframe.width = e.currentTarget.firstElementChild.width;
iframe.height = e.currentTarget.firstElementChild.height;
iframe.setAttribute('allowfullscreen', true);
iframe.src = 'https://www.youtube-nocookie.com/embed/' + video_id +
'?autoplay=true' + (options ? '&' + options : '');
e.currentTarget.parentElement.replaceChild(iframe, e.currentTarget);
e.preventDefault();
};
for (i = 0, max = els.length; i < max; i++) {
el = els[i];
el.addEventListener('click', replace_with_iframe);
}
};
var MYSITE=MYSITE||{};MYSITE.yt_embed=function(e){"use strict";var t,r,n,a=e.getElementsByClassName("yt-embed"),i=function(t){var r=e.createElement("iframe"),n=t.currentTarget.href.split("=")[1],a=t.currentTarget.getAttribute("data-yt-options");r.width=t.currentTarget.firstElementChild.width,r.height=t.currentTarget.firstElementChild.height,r.setAttribute("allowfullscreen",!0),r.src="https://www.youtube-nocookie.com/embed/"+n+"?autoplay=true"+(a?"&"+a:""),t.currentTarget.parentElement.replaceChild(r,t.currentTarget),t.preventDefault()};for(r=0,n=a.length;n>r;r++)t=a[r],t.addEventListener("click",i)};
<style>
iframe { border: 0; }
</style>
<a href="https://www.youtube.com/watch?v=VIDEOID" class="yt-embed" data-yt-options="autohide=1&amp;color=white&amp;rel=0&amp;showinfo=0&amp;theme=light">
<img src="poster.jpg" alt="YouTube video" width="320" height="180">
</a>
<script src="yt-embed.min.js"></script>
<script>
MYSITE.yt_embed(window.document);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment