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
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.
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.
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.
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
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