Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tell html doc not to load js if mobile device

I'm cheekily seeking a line or two of code on the fly here:

Could someone be kind enough to provide code to place in the head section of html doc that says if mobile then do not load JS?

This is being used in conjunction with the following CSS media query:

<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="m/styles_mobile.css" />

So I'm looking for a piece of code that is based on the same rule: media="only screen and (max-device-width: 480px)"

Would be very grateful

like image 850
Doug Fir Avatar asked May 09 '12 01:05

Doug Fir


People also ask

How to check if mobile device JavaScript?

To detect if the user is using a mobile device in JavaScript, we can use the userAgent property. This property is part of the navigator object and sent by the browser in HTTP headers. It contains information about the name, version, and platform of the browser.

How do I find a device in HTML?

If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code: if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i. test(navigator.


2 Answers

Given: "if mobile then do not load JS", and presuming "mobile" is defined by screens with a width of 480 pixels or less, then something like the following should work:

<script>
if (screen && screen.width > 480) {
  document.write('<script type="text/javascript" src="foo.js"><\/script>');
}
</script>

That will add the script element only if the screen is greater than 480 pixels wide.

The CSS rule in the OP is:

<... media="only screen and (max-device-width: 480px)" ...>

which will target screens of 480 pixels or less, which is contrary to to the first statement. Therefore change > to <= if the script should run on small screens and not run on larger ones.

like image 145
RobG Avatar answered Sep 16 '22 18:09

RobG


I'm not sure how the previous answers would go with retina displays. I would do something like:

if( /Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent))
 document.write('<script type="text/javascript" src="foo.js"><\/script>');

snippet from here

like image 20
Dave Avatar answered Sep 16 '22 18:09

Dave