Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load jQuery script in desktop browser, but not mobile [duplicate]

Tags:

jquery

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>
like image 773
rossautomatica Avatar asked Mar 31 '13 18:03

rossautomatica


1 Answers

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 */ }
});
like image 172
Travis J Avatar answered Oct 03 '22 14:10

Travis J