0

I'm trying to load only the few first seconds of an html5 video tag.

Alternatively, I could rephrase and say that I'd like to start a video, let it play for a few seconds and then stop it completely from loading (it's ok by me to hide the video element, if it matters).

Help please. Thanks!

Tomer Domshlak
  • 397
  • 1
  • 8
  • when the video starts, set a timer (either using setTimeout, or tracking the timechanged on the video itself) and at the appropriate time pause the video and (if you want to ensure it doesn't keep buffering) set the src to null – Offbeatmammal Dec 29 '20 at 23:44

2 Answers2

4

You could use the media-fragment syntax in the url to let the browser know which portion of the media it should play.

For instance, to tell it to play only the 5 first seconds of your media you would set your url to

https://www.example.com/example.mp4#t=0,5

document.querySelector("button").onclick = ({target}) => {
  target.remove();
  document.querySelector("video").play();
};
video { max-height: 100vh; }
<button>play</button>
<video muted src="https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm#t=0,5"></video>

The browser may preload more data than just this portion, but it should give it enough of an hint to not preload too much. Also, beware that if you let the user play with the controls of the video, they can easily over-pass that range.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

well, the solution to that is to set a load event to the window object so your code will be fired after the whole page has loaded.

or you can set DOMContentLoaded this event will be fired after the dom has loaded this will not wait for other resources like images stylesheets and so on...

for more information about those two events follow this article.
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

to get more information about setTimeout function see the below article https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

code snippet:

window.addEventListener("load", () => {
    setTimeout(() => {
        // select the video you want to hide, then set display property to none
        document.querySelector("video").style = "display: none;";
    }, delay);
});
Mouhamedou
  • 21
  • 4