Using Media Queries To Only Include JS Files On Mobile

こ雲淡風輕ζ 提交于 2019-12-17 20:24:10

问题


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

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.

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

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


回答1:


How about using javascript for that?

<script type="text/javascript">

if (screen.width < 980) { 

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

</script>



回答2:


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

Either way, you will need this:

enquire.js

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




回答3:


Light weight and works everywhere w/o the overhead.

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


来源:https://stackoverflow.com/questions/18946403/using-media-queries-to-only-include-js-files-on-mobile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!