Skip to content

Instantly share code, notes, and snippets.

@LyudmilaM
Created January 18, 2022 08:36
Show Gist options
  • Save LyudmilaM/b9b76afc82006da700e035e9e4b36b1e to your computer and use it in GitHub Desktop.
Save LyudmilaM/b9b76afc82006da700e035e9e4b36b1e to your computer and use it in GitHub Desktop.
Отложенная загрузка видео с youtube - загрузка iframe при клике на превью-картинку видео.
// Подгрузка iframe видео с ютуба
// при нажатии на превью
(function () {
// Делаем загрузку превью для видео (poster),
// а затем - создание iframe
let videos = document.querySelectorAll('.ytvideo');
videos.forEach((video) => {
video.style.backgroundImage = 'url(//img.youtube.com/vi/' + video.getAttribute('id') + '/maxresdefault.jpg)';
video.classList.add('poster');
video.addEventListener('click', function(e) {
let iframe = document.createElement('iframe');
let iframe__url = 'https://www.youtube.com/embed/' + this.getAttribute('id') + '?autoplay=1&autohide=1';
iframe.setAttribute('src', iframe__url);
if(this.getAttribute('title')){
iframe.setAttribute('title', this.getAttribute('title'));
}
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture');
iframe.setAttribute('allowfullscreen', '');
iframe.style.width = getComputedStyle(this).width;
iframe.style.height = getComputedStyle(this).height;
this.replaceWith(iframe);
});
});
})();
.videosBlock
.ytvideo(title="Слайдер swiper")#ddbxsrGPRY0
.ytvideo__button
.ytvideo(title="Создание сайта Halloween")#lgo1CEPZoxg
.ytvideo__button
.ytvideo(title="Coding music")#M5QY2_8704o
.ytvideo__button
.ytvideo
position: relative
width: 560px
height: 315px
cursor: pointer
background-size: cover
border: 1px solid gold
&:not(:last-child)
margin-bottom: 15px
&__button
position: absolute
top: 50%
left: 50%
display: block
width: 69px
height: 50px
background-image: url('../img/test/youtube-play-btn.png')
background-position: 0 -50px
background-size: 100% auto
border: 0
outline: none
transform: translate(-50%, -50%)
&:active,
&:focus
border: 0
outline: none
.ytvideo:hover
.ytvideo__button
background-position: 0 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment