Files
michaelschiemer/resources/js/utils/autoLoadResponsiveVideo.js

51 lines
1.6 KiB
JavaScript

// 📦 Automatischer Video-Loader (Bandbreiten- & Auflösungs-bewusst)
// Erkennt automatisch <video data-src="basename"> Elemente
// Lädt passende Variante: basename-480.webm, -720.webm, -1080.webm etc.
export function autoLoadResponsiveVideos() {
const videos = document.querySelectorAll('video[data-src]');
const width = window.innerWidth;
const connection = navigator.connection || {};
const net = connection.effectiveType || '4g';
videos.forEach(video => {
const base = video.dataset.src;
let suffix = '480';
if (net === '2g' || net === 'slow-2g') {
suffix = '480';
} else if (net === '3g') {
suffix = width >= 1200 ? '720' : '480';
} else {
suffix = width >= 1200 ? '1080' : width >= 800 ? '720' : '480';
}
const src = `${base}-${suffix}.webm`;
const newVideo = document.createElement('video');
newVideo.autoplay = true;
newVideo.loop = true;
newVideo.muted = true;
newVideo.playsInline = true;
newVideo.poster = video.getAttribute('poster') || '';
newVideo.setAttribute('width', video.getAttribute('width') || '100%');
const source = document.createElement('source');
source.src = src;
source.type = 'video/webm';
newVideo.appendChild(source);
video.replaceWith(newVideo);
});
}
/*
<video data-src="/media/video" poster="/media/preview.jpg" width="100%">
<!-- Optionaler Fallback -->
<source src="/media/video-480.mp4" type="video/mp4"/>
</video>
*/