javascriptjqueryhtmlhtml5-video

Trying to load a lot of <video> tags on one page


I am loading a lot of videos onto a page with the video tag. The issue is that it takes a long time for all of the videos to load and if you are trying to load a specific video it may wait for others to load before it because there are so many.

My solution is to load the thumbnail of all of these videos on the page and when you click on the thumbnail have it switch to the video and load the video.

I am not sure how I should go about doing thing. I was going to use jQuery and when a user clicks the image make the video visible but I am not sure if when a video is set to hidden will it still try to load?

What is the best way to display a video with the video tag after a user clicks on an image with jQuery?


Solution

  • In general, browsers do load resources inside elements that are hidden by CSS, so that they can be un-hidden quickly. If you want to load only on command, you probably need to build the element dynamically and add it to the page only when needed. Something like:

    var video = $("<video/>"); 
    video.append($("<source/>").attr("src", "video.mp4").attr("type", "video/mp4");
    $("#placeholder").html(video);
    

    The easiest way to extend this to multiple videos would be to place the video URL as data on each of your images with the jQuery .data() method, and load the appropriate video URL from the image's data in one universal click handler.