Search code examples
htmlvideo-streaminghtml5-video

HTML Video Source element; Specify different vidieo sizes


I want to embed a video in a simple, largely JavaScript-free web page. But I have two versions, one at 1920x1080 and one at 960x540. Ideally, the latter should be used in a smaller embedded window to save the user download, but the former if they go full screen on a PC.

I was expecting to see something on the <Source> element, but could not find it. I would think that it is a very common requirement.

Is there a fairly easy way to do this? Or do we just make the user always use the big file?

(One option is to put the small one inline, and then put a direct link to the full video after it, if the user clicks the latter they get the full resolution.)

The video contains a lot of text, so the larger one does look better full screen. It is twice as large though. (Handbrake compressed at 30 quality.)

If there was some widely used JavaScript control that would be good. But I do not want to have a dependency on a large framework such as React or Angular. This is essentially a static web page.


Solution

  • There are no media queries available for the video tag. You're stuck with JS or HLS streaming to create responsive video on the web.

    Here's a simple JS example that will do what you are looking for.

    <div id="video"> </div>
    
    <script>
    
        //get screen width and pixel ratio
        var width = screen.width;
        var smallVideo= <smallvideo>;
        var bigVideo = <bigVideo>;    
        if (width<500){
            console.log("this is a very small screen, no video will be requested");
            }
    
        else if (width< 1400){
                console.log("let’s call this mobile sized");
                var videoTag = "\<video preload=\"auto\" width=\"100%\" autoplay muted controls src=\"" +smallVideo +"\"/\>";
                document.getElementById('video').innerHTML = videoTag;
                }
        else{
                var videoTag = "\<video preload=\"auto\" width=\"100%\" autoplay muted controls src=\"" +bigVideo +"\"/\>";
                document.getElementById('video').innerHTML = videoTag;
    
        }
    
    </script>