Reputation:
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>
Upvotes: 2
Views: 3822
Reputation: 8210
Update: I've included dynamic insertion based on the innerWidth
so this should be cool now, it includes a video on wide screens, and a gif on small ones.
HTML:
<div class="wrapper">
<div id="video-container">
<video></video>
</div>
<div id="gif-container">
<img src="gif.gif">
</div>
</div>
CSS:
#video-container {
display: none;
}
#gif-container {
display: block;
}
// Mobile first = win!
@media screen and (min-width: 40em) {
#video-container {
display: block;
}
#gif-container {
display: none;
}
}
JavaScript:
function videoOrImage() {
console.log('hit')
if(window.innerWidth > 800) {
document.getElementById('gif-container').innerHTML = ''
var container = document.getElementById('video-container')
container.innerHTML = '<video width="320" height="240" controls><source src="movie.mp4" type="video/mp4"><source src="movie.ogg" type="video/ogg">Your browser does not support the video tag.</video>'
}
else {
document.getElementById('video-container').innerHTML = ''
var container = document.getElementById('gif-container')
container.innerHTML = '<img src="https://placehold.it/200">';
}
}
window.onresize = videoOrImage();
Upvotes: 0
Reputation: 2645
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.
Upvotes: 3