phantom phantom - 1 year ago 65
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

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=">"';
else {
main.innerHTML = '<video width="640" height="360" controls="" autoplay=""><source src="" type="video/mp4"><source src="" type="video/webm"><source src="" type="video/ogg"></video>';

Tom Tom
Answer Source

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


To make sure you account for screens turning sideways.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download