user1937021
user1937021

Reputation: 10791

check when video starts playing after populating src

I use the following code to check if the user is on desktop or mobile, if on desktop the src="" attribute of the video sources is populated. All fine. After populating the src attribute, I want to check the video has loaded before displaying it. Is there a way to do this?

Thanks!

JS

 //video
    if($.browser.mobile)
    {
        console.log("is mobile")
       // it is mobile browser
    }
    else
    {
      console.log("is desktop")
       // no mobile browser
       var sources = document.querySelectorAll('video#patient-video source');
      // Define the video object this source is contained inside
      var video = document.querySelector('video#patient-video');
      for(var i = 0; i<sources.length;i++) {
        sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
      }
      // If for some reason we do want to load the video after, for desktop as opposed to mobile (I'd imagine), use videojs API to load
      video.load();
      video.muted= "muted";
      $(".main-area--cris-pro").addClass("loaded")
    }

To check if it's a mobile browser, I use the plugin:

detectmobilebrowser.js

My HTML is as follows:

 <video id="patient-video" width="100%" preload="none" poster="../../assets/img/patient-home-1600.jpg" autoplay loop>
            <source data-src="../../assets/video/patient-home-video-comp.mp4" src="" type="video/mp4">
            <source data-src="../../assets/video/patient-home-video-comp.webm" src="" type="video/webm">
            <source data-src="../../assets/video/patient-home-video-comp.ogv" src="" type="video/ogg">
          </video>

Upvotes: 0

Views: 105

Answers (1)

Rayon
Rayon

Reputation: 36609

Use canplaythrough event.

The canplaythrough event is fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

var sources = document.querySelectorAll('video#patient-video source');
var video = document.querySelector('video#patient-video');
for (var i = 0; i < sources.length; i++) {
  sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
video.muted = true;//Set boolean value
video.addEventListener('canplaythrough', function() {
  alert('Video Loaded!');
  video.muted = false;
  $(".main-area--cris-pro").addClass("loaded");
});

Upvotes: 2

Related Questions