Skip to content

Instantly share code, notes, and snippets.

@millermedeiros
Created March 29, 2011 06:21
Show Gist options
  • Select an option

  • Save millermedeiros/891886 to your computer and use it in GitHub Desktop.

Select an option

Save millermedeiros/891886 to your computer and use it in GitHub Desktop.
iPad HTML5 video quirks and hacks
/*
* Example how to preload HTML5 video on the iPad (iOS 3.2+)
* @author Miller Medeiros
* Released under WTFPL
*/
var vid = document.createElement('video');
vid.src = 'lol_catz.mp4';
document.getElementById('video-holder').appendChild(vid);
//this function should be called on a click event handler otherwise video won't start loading
function initVideo(){
vid.play(); //start loading, didn't used `vid.load()` since it causes problems with the `ended` event
if(vid.readyState !== 4){ //HAVE_ENOUGH_DATA
vid.addEventListener('canplaythrough', onCanPlay, false);
vid.addEventListener('load', onCanPlay, false); //add load event as well to avoid errors, sometimes 'canplaythrough' won't dispatch.
setTimeout(function(){
vid.pause(); //block play so it buffers before playing
}, 1); //it needs to be after a delay otherwise it doesn't work properly.
}else{
//video is ready
}
}
function onCanPlay(){
vid.removeEventListener('canplaythrough', onCanPlay, false);
vid.removeEventListener('load', onCanPlay, false);
//video is ready
vid.play();
}
/*
* Restart video on iPad iOS 3.2+
* @author Miller Medeiros
* Released under WTFPL
*/
function restartVideo(){
vid.currentTime = 0.1; //setting to zero breaks iOS 3.2, the value won't update, values smaller than 0.1 was causing bug as well.
vid.play();
}
//loop video
vid.addEventListener('ended', restartVideo, false);
/**
* Enforce a specific amount of decimal digits
* @author Miller Medeiros
* Released under WTFPL
*/
function enforcePrecision(n, nDecimalDigits){
return +(n).toFixed(nDecimalDigits);
}
//seek to random position but limiting (and enforcing) the number of decimal digits to 1 to avoid iOS bug
vid.currentTime = enforcePrecision(Math.random() * vid.duration, 1);
@DamageESP

Copy link
Copy Markdown

Thank you for this.

It finally made Audio work for Chrome in Android.

Such a bummer we have to use these hacky things but it is what it is. Thanks again, spent the whole day trying to fix this.

@metamao

metamao commented May 16, 2018

Copy link
Copy Markdown

Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment