Copie-colle ce script dans le <body> de ta page Ajout ce code qui va te permettre dé générer une façade pour ta vidéo et t'éviter de charger la vidéo Youtube immédiatement. Ce script te permet de retirer le chargement initial de la vidéo détecté par Page Speed Insight et de gagner considérablement en performance.
Copier
<script>
class YouTubeThumbnailLoader {
constructor(container, videoId, title = 'Vidéo') {
this.container = container;
this.videoId = videoId;
this.title = title;
this.loaded = false;
this.init();
}
init() {
// Créer la structure HTML
this.container.innerHTML = `
<div class="video-thumbnail loading-shimmer">
<div class="play-button" aria-label="Lire la vidéo ${this.title}"></div>
</div>
`;
this.thumbnail = this.container.querySelector('.video-thumbnail');
// Charger la thumbnail immédiatement
this.loadThumbnail();
// Ajouter l'événement de clic
this.container.addEventListener('click', () => this.loadVideo());
}
loadThumbnail() {
const img = new Image();
img.fetchPriority = 'high';
img.crossOrigin = 'anonymous';
img.src = `https://i.ytimg.com/vi/${this.videoId}/maxresdefault.jpg`;
img.onload = () => {
this.thumbnail.style.backgroundImage = `url(${img.src})`;
this.thumbnail.classList.remove('loading-shimmer');
this.thumbnail.classList.add('loaded');
};
img.onerror = () => {
// Fallback vers hqdefault
const fallbackImg = new Image();
fallbackImg.src = `https://i.ytimg.com/vi/${this.videoId}/hqdefault.jpg`;
fallbackImg.onload = () => {
this.thumbnail.style.backgroundImage = `url(${fallbackImg.src})`;
this.thumbnail.classList.remove('loading-shimmer');
this.thumbnail.classList.add('loaded');
};
};
}
loadVideo() {
if (this.loaded) return;
this.loaded = true;
// Créer l'iframe YouTube
const iframe = document.createElement('iframe');
iframe.className = 'video-iframe';
iframe.src = `https://www.youtube.com/embed/${this.videoId}?autoplay=1&rel=0&modestbranding=1`;
iframe.title = this.title;
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share';
iframe.allowFullscreen = true;
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.border = 'none';
// Remplacer le thumbnail par l'iframe
this.container.innerHTML = '';
this.container.appendChild(iframe);
}
}
// Auto-initialisation
document.addEventListener('DOMContentLoaded', function() {
const videoContainers = document.querySelectorAll('[data-youtube-id]');
videoContainers.forEach((container, index) => {
const videoId = container.getAttribute('data-youtube-id');
const title = container.getAttribute('data-video-title') || `Vidéo ${index + 1}`;
if (videoId) {
new YouTubeThumbnailLoader(container, videoId, title);
}
});
});
</script>
Tuto vidéo