M9A
M9A

Reputation: 3276

HTML5 Video loadeddata event does not work in IOS Safari

I am trying to trigger an event once a video has loaded the first frame. The code I have used works in desktop browsers that I have tested in but it does not work in mobile safari on IOS. Is there something about the code that is not supported on mobile safari or is there another solution to achieve what I want?

function loadvideo (vidsource){

var vid = document.createElement('video');
vid.src = vidsource;

alert("Video about to load"); //This works fine in mobile safari
vid.addEventListener('loadeddata', function() {
alert("Video Loaded!"); //This does not display in mobile safari
//Will do something else here
}, false);

}

Upvotes: 12

Views: 17809

Answers (3)

Oleksandr Tkach
Oleksandr Tkach

Reputation: 101

Add preload="metadata" to video tag and then listen to loadedmetadata event. It works in IOS Safari as well

Upvotes: 8

Suhaas Prasad
Suhaas Prasad

Reputation: 141

On iOS, it looks like the video doesn't get loaded unless the user hits play, or if the autoplay attribute has been added (which doesn't actually appear to autoplay it).

The following should work for you:

var vid = document.createElement('video');
if (/iPad|iPhone|iPod/.test(navigator.userAgent))
    vid.autoplay = true;
vid.addEventListener('loadeddata', function() {[...]}, false);
vid.src = videosource;

Alternatively, you can listen to the progress event instead of loadeddata, which seems to work fine on iOS Safari.

Upvotes: 14

Andrew Evt
Andrew Evt

Reputation: 3689

try not to use addEventListener is this case, use older on style, AND set src AFTER you setup an event listener:

...
vid.onloadeddata = function () {
    alert("Video Loaded!");
    // do something
}
vid.src = vidsource;
...

If an EventListener is added to an EventTarget while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase. - To learn more - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Upvotes: 1

Related Questions