phantom phantom - 2 months ago 7
HTML Question

serve different content for a mobile device than desktop

I am building a website and wish to serve a video if the user is on a desktop device, and if on a mobile I am going to serve a gif.

Does anyone have any guidance for best practices on this?

Is the below code enough? When I test this on chrome it doesn't show the mobile gif, but perhaps something is incorrect here.

Should I be using modernizr to cover browser/device inconsistencies I may not be aware of? Is there a

data-src
approach that I should be taking perhaps?

<div id="main"></div>

<script type="text/javascript">

var main = document.getElementById('main');

//check if a mobile device
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
main.innerHTML = '<img src="http://static1.squarespace.com/static/552a5cc4e4b059a56a050501/565f6b57e4b0d9b44ab87107/566024f5e4b0354e5b79dd24/1449141991793/NYCGifathon12.gif>"';
}
else {
main.innerHTML = '<video width="640" height="360" controls="" autoplay=""><source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4"><source src="http://clips.vorwaerts-gmbh.de/VfE.webm" type="video/webm"><source src="http://clips.vorwaerts-gmbh.de/VfE.ogv" type="video/ogg"></video>';
}
</script>



Tom Tom
Answer

Please do not test for a device, test for a screen size.

var windowWidth = $(window).width();
var maxDeviceWidth = 768;
if (windowWidth > maxDeviceWidth) {
    //Server the desktop version
    //You can get the content with Ajax or load both and hide the other
} else {
    //Load the mobile content - either with Ajax, or hide the desktop content
}

I'd suggest that you just load content with Ajax based on the screen width. Make sure you also put this in

$(window).resize();

To make sure you account for screens turning sideways.