Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...