El Atributo ONPROGRESS

El atributo onprogress permite monitorear el progreso de carga de recursos multimedia (audio/video).
El atributo onprogress
permite monitorear el progreso de carga de recursos multimedia (audio/video). Es esencial para:
-
Mostrar barras de progreso personalizadas
-
Gestionar la experiencia de carga
-
Optimizar la reproducción bajo conexiones lentas
-
Implementar feedback visual para el usuario
???? Sintaxis Básica
<!-- En HTML --> <audio|video onprogress="manejarProgreso(event)"> <!-- En JavaScript --> elementoMedia.onprogress = (event) => { ... }; elementoMedia.addEventListener('progress', callback);
???? Ejemplos Prácticos
1. Monitor Básico de Carga
<video id="miVideo" src="video.mp4" controls onprogress="actualizarProgreso(event)"> </video> <p>Buffered: <span id="buffered">0%</span></p> <script> function actualizarProgreso(event) { const video = event.target; const duration = video.duration; if (duration > 0 && video.buffered.length > 0) { const buffered = video.buffered.end(0); const porcentaje = (buffered / duration) * 100; document.getElementById('buffered').textContent = `${Math.round(porcentaje)}%`; } } </script>
2. Barra de Progreso Personalizada
<video id="videoPlayer" src="presentacion.mp4" onprogress="actualizarBarra()"></video> <div class="progress-container"> <div id="bufferBar" class="buffer-progress"></div> </div> <style> .progress-container { width: 100%; height: 5px; background: #ddd; margin: 10px 0; } .buffer-progress { height: 100%; width: 0%; background: #2ecc71; transition: width 0.3s ease; } </style> <script> function actualizarBarra() { const video = document.getElementById('videoPlayer'); const duration = video.duration; if (duration && video.buffered.length > 0) { const bufferEnd = video.buffered.end(0); const width = (bufferEnd / duration) * 100; document.getElementById('bufferBar').style.width = `${width}%`; } } </script>
3. Sistema de Precarga Inteligente
<audio id="audioPlayer" onprogress="manejarPrecarga()"></audio> <button onclick="cargarAudio('musica.mp3')">Cargar Música</button> <div id="loadStatus">Estado: No cargado</div> <script> function cargarAudio(src) { const audio = document.getElementById('audioPlayer'); audio.src = src; audio.load(); } function manejarPrecarga() { const audio = document.getElementById('audioPlayer'); const porcentaje = (audio.buffered.end(0) / audio.duration) * 100; document.getElementById('loadStatus').innerHTML = ` <p>${Math.round(porcentaje)}% cargado</p> ${porcentaje >= 50 ? '<button onclick="audioPlayer.play()">Reproducir</button>' : ''} `; } </script>
???? Funcionamiento Clave
-
Propiedades del Evento:
-
buffered
: Rango de tiempo cargado -
length
: Número de rangos cargados -
duration
: Duración total del recurso
-
-
Métodos Útiles:
// Obtener el final del primer rango cargado const bufferEnd = media.buffered.end(0); // Calcular progreso total const progress = (bufferEnd / media.duration) * 100;
???? Consideraciones Importantes
-
Compatibilidad:
Navegador Soporte Chrome ✅ 3+ Firefox ✅ 3.5+ Safari ✅ 5+ Edge ✅ 12+ -
Mejores Prácticas:
-
Combinar con
onwaiting
yonplaying
para manejar estados de carga -
Usar
preload="auto"
para iniciar carga automática -
Verificar
media.readyState
para estados de carga avanzados
-
???? Casos de Uso Avanzados
1. Priorización de Carga
function priorizarCarga(mediaElement) { const priorityRanges = [ {start: 0, end: 15}, // Primeros 15 segundos {start: mediaElement.duration - 30, end: mediaElement.duration} // Últimos 30 segundos ]; mediaElement.onprogress = () => { priorityRanges.forEach(range => { if(!mediaElement.buffered.length || mediaElement.buffered.end(0) < range.end) { mediaElement.currentTime = range.start; } }); }; }
2. Adaptación Dinámica de Calidad
const qualityLevels = { low: 'video_240p.mp4', medium: 'video_480p.mp4', high: 'video_1080p.mp4' }; function actualizarCalidad() { const video = document.getElementById('videoPlayer'); const cargaActual = video.buffered.end(0) - video.currentTime; if(cargaActual < 10) { video.src = qualityLevels.low; } else if(cargaActual < 20) { video.src = qualityLevels.medium; } else { video.src = qualityLevels.high; } video.play(); }
⚠️ Solución de Problemas Comunes
Problema: La barra de progreso no se actualiza
// Verificar si la duración es válida if(isNaN(media.duration) { media.onloadedmetadata = () => actualizarProgreso(); }
Problema: Buffering intermitente
// Implementar estrategia de rebote let timeout; media.onprogress = () => { clearTimeout(timeout); timeout = setTimeout(actualizarProgreso, 300); };
???? Conclusión
El atributo onprogress
permite:
-
Crear experiencias multimedia interactivas
-
Implementar sistemas de precarga inteligente
-
Adaptar contenido a condiciones de red
-
Mejorar la percepción de rendimiento
Ejemplo Final Avanzado (Streaming Adaptativo):
<video id="streamPlayer" onprogress="gestionarStream()"></video> <script> const bitrates = [ { res: '720p', src: 'stream_high.mpd', minBuffer: 20 }, { res: '480p', src: 'stream_med.mpd', minBuffer: 10 }, { res: '240p', src: 'stream_low.mpd', minBuffer: 5 } ]; function gestionarStream() { const video = document.getElementById('streamPlayer'); const bufferActual = video.buffered.end(0) - video.currentTime; const calidadOptima = bitrates.find(({ minBuffer }) => bufferActual >= minBuffer); if(calidadOptima && video.src !== calidadOptima.src) { video.src = calidadOptima.src; video.play(); } } </script>
Con estos conceptos, podrás crear reproductores multimedia profesionales y optimizados. ¡Experimenta con diferentes implementaciones! ????????