Html – How to make a loading image when loading HTML5 video

htmlvideovideo streaming

As it takes time for the video player to load the mp4 video, does HTML5 support playing a "loading" logo when loading the video ?

enter image description here

Since my asp.net apps is a mobile page, it needs the user to click on the video to play the video (android, iphone not support autoplay). So, I cannot make a "loading" logo as poster, otherwise, the user will be confused about it. I want to display a loading logo when user click play button on iPad.

thanks

Joe

Best Answer

It took me a way too long to actually figure out how to do this, but I'm going to share it here because I FINALLY found a way! Which is ridiculous when you think about it, because loading is something that all videos have to do. You'd think they would have taken this into account when creating the html5 video standard.

My original theory that I thought should have worked (but wouldn't) was this

  1. Add loading bg image to video when loading via js and css
  2. Remove when ready to play

Simple, right? The problem was that I couldn't get the background image to show when the source elements were set, or the video.src attribute was set. The final stroke of genius/luck was to find out (through experimentation) that the background-image will not disappear if the poster is set to something. I'm using a fake poster image, but I imagine it would work as well with a transparent 1x1 image (but why worry about having another image). So this makes this probably a kind of hack, but it works and I don't have to add extra markup to my code, which means it will work across all my projects using html5 video.

HTML

<video controls="" poster="data:image/gif,AAAA">
    <source src="yourvid.mp4"
</video>

CSS (loading class applied to video with JS)

video.loading {
  background: black url(/images/loader.gif) center center no-repeat;
}

JS

  $('#video_id').on('loadstart', function (event) {
    $(this).addClass('loading');
  });
  $('#video_id').on('canplay', function (event) {
    $(this).removeClass('loading');
    $(this).attr('poster', '');
  });

This works perfectly for me but only tested in chrome and safari on mac. Let me know if anyone finds bugs and or improvements!