I want to load a particular jQuery script/function in desktop browsers, but not mobile browsers. At the moment, the script runs very slow on mobile browsers, but works fine on desktop browsers.
The function in question is a smooth scrolling plugin, so that when a user clicks a link, the page scrolls smoothly to the anchor on the same page. It is not necessary for it to scroll smoothly on mobile browsers - it is too slow, and often doesn't work.
What would I need to add to my code below to ensure that it is still executed as normal in desktop browsers, but not mobile (particularly iPad/iPhone/iPod)?
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/lib/jquery/jquery.js"%3E%3C/script%3E'));</script>
<script src="js/css_browser_selector.js"></script>
<script src="js/src/jquery.smooth-scroll.js">
</script>
<script src="js/lib/jquery.ba-bbq.js"></script>
<script>
$(document).ready(function() {
$('a[href*="#"]').live('click', function() {
if ( this.hash ) {
$.bbq.pushState( '#/' + this.hash.slice(1) );
return false;
}
});
$(window).bind('hashchange', function(event) {
var tgt = location.hash.replace(/^#\/?/,'');
if ( document.getElementById(tgt) ) {
$.smoothScroll({scrollTarget: '#' + tgt});
}
});
$(window).trigger('hashchange');
});
</script>
jsFiddle Demo
Look for the existence of touch
, if it is not present then you are more than likely dealing with a desktop:
edit: my original try/catch approach was apparently deprecated ( https://stackoverflow.com/a/4819886/1026459 )
$(document).ready(function() {
var isDesktop = (function() {
return !('ontouchstart' in window) // works on most browsers
|| !('onmsgesturechange' in window); // works on ie10
})();
//edit, if you want to use this variable outside of this closure, or later use this:
window.isDesktop = isDesktop;
if( isDesktop ){ /* desktop things */ }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With