Search code examples
javascriptvideoresponsive-designhtml5-videopageload

HTML5 video with different files for responsive design


Is there a srcset equivalent for HTML5 video? At present I have a grid of videos on a page, 3 in a row, in 5 rows (so 15 videos in total) all like this:

<video width="400" poster="14.jpg" loop="loop" autoplay="autoplay">
  <source src="14.webm" type="video/webm">
  <source src="14.mp4" type="video/mp4">
</video>

The issue I'm having is that my page request is up to about 6mb. As the grid of videos I have are 3 wide...

<div class="row">
  <video width="400" poster="13.jpg" loop="loop" autoplay="autoplay">
    <source src="13.webm" type="video/webm">
    <source src="13.mp4" type="video/mp4">
  </video>
  <video width="400" poster="14.jpg" loop="loop" autoplay="autoplay">
    <source src="14.webm" type="video/webm">
    <source src="14.mp4" type="video/mp4">
  </video>
  <video width="400" poster="15.jpg" loop="loop" autoplay="autoplay">
    <source src="15.webm" type="video/webm">
    <source src="15.mp4" type="video/mp4">
  </video>
</div>

...its pretty obvious that for a small device with a screen size of ~ 320px I don't need 3 400px video files, I could use smaller ones.

I'm just about to start refactoring to load my page like this:

<div class="row">
  <video width="400" poster="13.jpg" loop="loop" autoplay="autoplay">
  </video>
  <video width="400" poster="14.jpg" loop="loop" autoplay="autoplay">
  </video>
  <video width="400" poster="15.jpg" loop="loop" autoplay="autoplay">
  </video>
</div>

And then use JavaScript to essentially say:

if($(window).width() < 500){
    $('#video13').append('<source src="13-SMALL-FILE.mp4" type="video/mp4">')
}else{
    $('#video13').append('<source src="13-LARGE-FILE.mp4" type="video/mp4">')
}

Is that a good option or is there a better way or a library that already exists? After Googling a lot I haven't found very much helpful information.


Solution

  • Video and picture elements have long supported the media attribute, so you can do a variety of things, including:

    <video  playsinline muted preload="metadata">
        <source src="" type="" media="(orientation: landscape)">
        <source src="" type="" media="(orientation: portrait)">
    </video>
    

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source#using_the_media_attribute_with_video