Modernizr is wonderful and pretty much becoming as prevalent as JQuery. I’m not going to further evangelize Modernizr as there’s so many resources that can summarize Modernizr better than me. We’ll skip the introductions and assume you’re familiar with Modernizr. If you aren’t, google it and you’re in for a treat :)

Modernizr isn’t quite enough for background video

I was working on a proof of concept codepen.io project and needed to do one of the most basic of things: Load a background video but only on desktop device. . Its pretty easy to craft a Modernizr script show/hide content on touch and video takes as such. However, Modernizr doesn’t make a distinction between mobile and non-mobile.

html
<video autoplay loop id="bgvid">
<source src="video.mp4" type="video/mp4">
</video> 

Javscript
if( Modernizr.touch &|| !Modernizr.video){
var isMobile = true;
$("#html5-video").show();
}else{
var isMobile = false;
$("#html5-video").hide();
}

Getting smarter

The problem with the above is the video is still being loaded into the DOM.  Its not ideal as Modernzr alone isn’t quite enough to target just mobile devices where users are likely going to be on data plans. 

We can leverage JQuery to make this smarter using the .html() attribute. 

html
<script type="text/html" id="video-tpl">
<video autoplay loop id="bgvid">
<source src="video.mp4" type="video/mp4">
</video>
</script>
<div="target></div>

Javascript
var $target = $("#target"),

videoTpl = $("#video-tpl").html();
if( Modernizr.touch || !Modernizr.video){ 
var isMobile = true; 
$target.html(videoTpl);
}else{ 
var isMobile = false;
}

The beauty of the above example is that the <video> tag will be completely ignored when we do not want it to be used. However, Some windows 8 devices despite running Windows 8 desktop may be eliminated because of our conditional statement, as Modernizr will detect the touch functionality.

WURFL to the rescue

Head.js is a viable option (its a cousin to Modernizr, tossing plenty of body classes onto the HTML)  as it’ll put a  .mobile class onto your body. However, you’re probably going to get more accurate device definitions from WURFL as it’s been around for several years uses a well established device database.

So with a single conditional change from modernizr for touch to WURFL.is_mobile, we can more accurately detect mobile only devices.

html
<script type="text/html" id="video-tpl">
<video autoplay loop id="bgvid">
<source src="video.mp4" type="video/mp4">
</video> 
</script>
<div="target></div>

Javascript
var $target = $("#target"),
videoTpl = $("#video-tpl").html();
if( WURFL.is_mobile || !Modernizr.video){ 
var isMobile = true; 
$target.html(videoTpl);
}else{ 
var isMobile = false;
}

That’s it, now our background video will be ignored if the browser does NOT support <video> or is a mobile device.