Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari reloading in-memory video

In Chrome, when a <video> is created with a given <source>, the video loads once, then any subsequently created <video> elements with the same <source> use the in-memory video (as expected).

On Safari (12.0), new videos with the same source are reloaded each time even though the video is already in-memory!

console.log("Loading the first video...");  
createVideo("https://ciliar.co/video/beach.mp4", () => {
  console.log("First video fully loaded!");
  
  console.log("Loading the second video...");
  createVideo("https://ciliar.co/video/beach.mp4", () => {
    console.log("Second video fully loaded!");
  });
});


// Helper to create video elements with a given url and call onFullyLoaded once the video can play through fully.
function createVideo(url, onFullyLoaded) {
  const vid = document.createElement("video");
  vid.setAttribute("preload", "auto");
  vid.oncanplaythrough = onFullyLoaded;

  const source = document.createElement("source"); 
  source.type = "video/mp4";
  source.src = url;
  
  vid.appendChild(source);
  document.body.appendChild(vid);
}

When the above is run in Chrome vs Safari you can see how the second video loads 'instantly' on Chrome but re-loads and takes a little while on Safari.

How can I get Safari to re-use an in-memory video when a new element has the same source as a previous one? My end goal is to preload a video before it displays (the first video would be display: none).

like image 276
abagshaw Avatar asked Nov 07 '22 01:11

abagshaw


1 Answers

As Apple doesn't in any way allow Safari development without paying them hundreds of euros/dollars I can't check this, but:

What about just passing the cached video element around

vid.oncanplaythrough = () => {
    document.removeChild(vid); // not really necessary
    onFullyLoaded(vid);
};

and then use that element anywhere else on the page you need it.

The only alternative would be to create an in memory stream from the first element for the second (as it's fully loaded it might not even be necessary to create a stream), but that will probably double the memory requirement which would be undesirable.

like image 116
David Mulder Avatar answered Nov 14 '22 22:11

David Mulder