Skip to content

Instantly share code, notes, and snippets.

@alexwebgr
Created May 30, 2019 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexwebgr/b8b44b26b70a83df02a86f47af086e63 to your computer and use it in GitHub Desktop.
Save alexwebgr/b8b44b26b70a83df02a86f47af086e63 to your computer and use it in GitHub Desktop.
Load youtube videos async
let videos = $(".wpl-youtube");
$.each(videos, function () {
let self = $(this);
let thumbnail = self.find('img');
let play = self.find('.wpl-play');
// Based on the YouTube ID, we can easily find the thumbnail image
thumbnail.attr('src', 'https://i.ytimg.com/vi/' + self.attr('data-id') + '/0.jpg');
play.on({
click: function () {
// Create an iFrame with autoplay set to true
let iframe = $("<iframe />");
let iframe_url = "https://www.youtube-nocookie.com/embed/" + self.attr('data-id') + "?autoplay=1&autohide=1&rel=0&amp;showinfo=0";
if (self.attr("data-params")) iframe_url += '&' + self.attr("data-params");
iframe.attr("src", iframe_url);
iframe.attr("frameborder", '0');
iframe.attr("class", 'embed-responsive-item');
iframe.attr("allow", 'autoplay; encrypted-media');
iframe.attr("allowfullscreen", true);
// The height and width of the iFrame should be the same as parent
self.attr('class', 'embed-responsive embed-responsive-16by9');
// Replace the YouTube thumbnail with YouTube Player
self.html(iframe);
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment