javascript 使用媒体查询仅在移动设备上包含 JS 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18946403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:46:26  来源:igfitidea点击:

Using Media Queries To Only Include JS Files On Mobile

javascriptcssmobile

提问by Joshua Soileau

I am trying to use the media attribute to only link my javascript files on to mobile devices, not on desktop ones.

我正在尝试使用媒体属性仅将我的 javascript 文件链接到移动设备,而不是桌面设备。

Here's my link tag:

这是我的链接标签:

<script type="text/javascript" media="screen and (max-width : 850px)" src="mobile.js"></script>

But this isn't working, it links to JS to everything.

但这不起作用,它链接到 JS 到所有内容。

How do I only link a JS file if it meets those query conditions?

如何只链接符合这些查询条件的 JS 文件?

If I can't how do I only run JS if it is on mobile?

如果我不能,我如何只在移动设备上运行 JS?

回答by frenchie

How about using javascript for that?

使用 javascript 怎么样?

<script type="text/javascript">

if (screen.width < 980) { 

    document.write('<script type="text/javascript" src="mobile.js"></script>');  
 } 

</script>

回答by jshthornton

There are two ways you can do this:

有两种方法可以做到这一点:

  1. Have all of your scripts on the page already and invoke them when the breakpoints are triggered
  2. Load your scripts only when they are needed, once a breakpoint is met
  1. 将所有脚本都放在页面上,并在触发断点时调用它们
  2. 一旦遇到断点,仅在需要时加载脚本

Either way, you will need this:

无论哪种方式,你都需要这个:

enquire.js

查询.js

This will allow you to add media queries callbacks for js.

这将允许您为 js 添加媒体查询回调。

回答by jshthornton

Light weight and works everywhere w/o the overhead.

重量轻,可在任何地方工作,无需开销。

if (document.documentElement.clientWidth < 900) {   // scripts }