user5175904
user5175904

Reputation:

Including JS script conditional to user device

I need to load a script conditionally so that it only loads on desktop/laptops. I need it NOT to show on mobile/tablet. (So I'm guessing filtering by screen width would be best.)

<script type='text/javascript' src='//xxxxxxxx.com/xxxx.php?zoneid=354066'></script>

I've looked at including it like this to no avail:

<script type="text/javascript">

var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");

js.type = "text/javascript";

if (screen.width > 500)
{
}
else
{
    js.src = "//xxxxxxxx.com/xxxx.php?zoneid=354066";
}

head.appendChild(js);
</script>

Any ideas?

Upvotes: 2

Views: 55

Answers (1)

Pavan Ravipati
Pavan Ravipati

Reputation: 1870

You can use navigator.userAgent. You should replace .match(/Mac/) with the pattern for the type of desktop you're looking to target. You can also use "or" -- || to check for multiple types of desktops :

var ua = window.navigator.userAgent;

if (ua.match(/Mac/) != null){ 
  var js = document.createElement('script');
  js.type = "text/javascript";
  js.src = "//xxxxxxxx.com/xxxx.php?zoneid=354066'";

  var head = document.getElementsByTagName('head')[0];
  head.appendChild(js);
}

Upvotes: 1

Related Questions