MaxelRus MaxelRus - 2 months ago 26
jQuery Question

HTML5 video preload solution

I'm creating a website with some animations. One of them is the logo animation. It's called 'lbv.mp4'. As it has some weight, there's a lag with autoplay, so I decided to show content when it is fully loaded.

The plan is:


  • the video is checked for loading

  • start the video

  • add a class to the page element to trigger the animation

  • setTimeout
    for the length of the video which will make
    visibility: hidden
    for the clip to open a static image underneath.



This is better described in the following code:

video.addEventListener('loadeddata', function () {
if (video.readyState === 4) {
video.play();
$('#page').addClass('transition');
document.setTimeout(function(){
video.attr('style', 'visibility: hidden');
}, 750);
}


The only problem is that I can't get it working neither with pure JS, neither with JQuery. The video isn't loading, the classes aren't given. Tested in Safari, Chrome and Firefox.

So the final question is: 'Is there another to make it easier, or how to fix my solution?'

Answer

Event loadeddata means :

The first frame of the media has finished loading.

readyState === 4 means :

Enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption.

You have chances that loadeddata is triggered but readyState is not 4. Since loadeddata is triggered only once, the video won't ever play.

You should try to add logs to verify this assumption.

What I would try is the following :

  • Use <video> with autoplay
  • Listen for the playing event on the video to start transition
  • Listen for the ended event on the video to hide it

Reference for attributes, events and readyState: