Benjamin Charity

Load script only on mobile browser

January 14th 2011

Sometimes you may need to only load a script when your site is viewed from a mobile browser.  This little bit of Javascript can do just that.

<script>
  <!--
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/android/i)) ||         (navigator.userAgent.match(/opera/i)) || (navigator.userAgent.match(/blackberry/i)) || (navigator.userAgent.match(/palm/i)) ||        (navigator.userAgent.match(/windows/i)))
    {
      YOUR_SCRIPT_HERE
    }
  -->
</script>

Conversely, you simply add an ! in the if statement to only load a script when the browser is not a mobile browser.

<script>
  <!--
    if(!(navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/android/i)) ||        (navigator.userAgent.match(/opera/i)) || (navigator.userAgent.match(/blackberry/i)) || (navigator.userAgent.match(/palm/i)) ||        (navigator.userAgent.match(/windows/i)))
    {
      YOUR_SCRIPT_HERE
    }
  -->
</script>