Search code examples
javascripthtmlvideowindow

Change video source on screen size


I want to switch the source of a video depending on screen size. So that it is loading a small and a large video. I hope, that my site perform/loads faster. At the moment it is working with jQuery, but I want it in pure javascript.

My HTML:

<div class="video-section">
<div id="video-wrapper">
<video autoplay="" muted="" loop="" id="myVideo" preload="auto"></video>
</div>

Here is my jQuery code:

const mainVideo = $('#myVideo');
    
const medi      = "/videos/ground_540p.mp4";
const large     = "/videos/ground_1080p.mp4";

  switch ( true ) {

      case ($(window).width() >= 1080):
          mainVideo.append("<source type='video/mp4' src='" + large + "' />");
          break;

      case ($(window).width() >= 720):
          mainVideo.append("<source type='video/mp4' src='" + medi + "' />");
          break;
  
  }

That is my pure javascript:

const mainVideo = document.getElementById("myVideo");
    
const medi      = "/videos/ground_540p.mp4";
const large     = "/videos/ground_1080p.mp4";

  switch ( true ) {

      case window.innerWidth >= 1080:
          mainVideo.append("<source type='video/mp4' src='" + large + "' />");
          break;

      case window.innerWidth >= 720:
          mainVideo.append("<source type='video/mp4' src='" + medi + "' />");
          break;
  
  }

In my firefox inspector it is displayed, but it is grey. It is not showing(not loading) Here is a image: enter image description here

I hope, this a good way.. and my video is not loading twice.

Edit: I did i like this:

<div class="video-section">
<div id="video-wrapper">
<video autoplay="" muted="" loop="" id="myVideo" preload="auto">
  <source src="/videos/ground_1080p.mp4" media="(min-width: 1200px)" />
  <source src="/videos/ground_540p.mp4" media="(min-width: 768px)" />
  I'm sorry; your browser doesn't support HTML video.
</video>

Is it loading twice now?


Solution

  • A HTML-only approach could work in your case, as well.
    Assumptions:

    1. the code showcased in the question is not inside a eventHandler
    2. you want the HTML to handle video source at page load

    The best reference is here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source#using_the_media_attribute_with_video

    Note: Avoid parsing markup through JS as it is considered insecure.