jroy
jroy

Reputation: 565

HTML5 video: stalled event

I'm writing a video player using HTML5 video tags on Google Chrome: I need to show some videos (1), then remove them from the DOM document to show other videos and later create again some video tags pointing to the same files than (1).

I noticed that sometimes the videos are not showing the second time I load them, instead a 'stalled' event is fired...What am I supposed to do to handle this event and be able to show the videos? If I keep a reference to the first video tag then reuse it later it works, but keeping a reference to each video tag could be very memory-consuming!

Upvotes: 4

Views: 5154

Answers (1)

brianchirls
brianchirls

Reputation: 7853

If you have more than two or three videos that the browser is trying to load at one time, some of them are going to stall. Although HTML5 video provides a way to tell it to start loading videos, there's no way to tell it to stop. Once you start playing it the first time, as long as it's in memory, it's going to keep trying to load more data in case you decide to start playing it again. And it will only load so many videos at a time, so if you're still loading the first three videos, the fourth one will wait for a very, very long time.

Removing the old videos and loading them again later is the right approach, but you need to be very thorough about it to make the browser stop trying to load them. Here's what you need to do.

// 1) Pause the video
oldVideo.pause();

// 2) Clear the video source URL
oldVideo.src = "";

// 3) Tell the video to start loading "nothing"
oldVideo.load();

That last step is crucial. Even once you set src to an empty string, the video will ignore it until you call load. If you want, you can remove it from the DOM and any of your data structures as well so it can be fully garbage collected. But even if you do that, it won't be garbage collected unless you clear the src and call load.

The next time you load the video, either by creating a new element or setting the src on the same one, it should work just fine.

Upvotes: 6

Related Questions