Tell html doc not download js if mobile device

I am looking for a line or two code on the fly here:

Could someone please be kind enough to provide the code to be placed in the html doc header section, which says if the mobile does not load JS?

This is used in conjunction with the following CSS format request:

<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 code snippet based on the same rule: media = "only screen and (max-device-width: 480px)"

I would be very grateful

+7
source share
4 answers

Given: β€œif mobile, and then does not load JS, ” and assuming that β€œmobile” is defined by screens with a width of 480 pixels or less, then the following should work:

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

This will add a script element only if the screen size is more than 480 pixels.

CSS rule in OP:

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

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

+20
source

I'm not sure how the previous answers will appear on the mesh 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>'); 

fragment from here

+11
source

You can do it as follows.

  • Check the width and height of the screen to see if it is a mobile device.
  • Loading scripts using JavaScript.

What you can do is:

 var scripts = ["foo.js", //Put all your scripts here. "bar.js"]; if(screen.width <= 480){ for(var i=0;i<scripts.length;i++){ //-with jQuery (one line!)- $("head").append('<script type="text/javascript" src="'+scripts[i]+'"><\/script>'); //-or jQuery free- var scriptEle = document.createElement("script"); scriptEle.setAttribute("type","text/javascript"); scriptEle.setAttribute("src",scripts[i]); document.getElementsByTagName("head")[0].appendElement(scriptEle); } } 

Note that this is screen.width <= 480 .

+5
source

Now you can use window.matchMedia

 if (window.matchMedia("(min-width: 480px)").matches) { document.write('<script type="text/javascript" src="foo.js"><\/script>'); } 

https://developer.mozilla.org/docs/Web/API/Window/matchMedia http://caniuse.com/#feat=matchmedia

+4
source

All Articles