如何根据屏幕分辨率加载或不加载JS脚本(到头部)? [英] How to load or not a JS script (into the head section) based on screen resolution?
本文介绍了如何根据屏幕分辨率加载或不加载JS脚本(到头部)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在网站上,标签上有这些行
on a website, I have these lines on the tag
<script type="text/javascript" src="http://www.domain.com/js/jquery.min.js"></script>
<script type="text/javascript" src="http://www.domain.com/js/jquery.colorbox.min.js"></script>
<script type="text/javascript" src="http://www.domain.com/js/inner-code-colorbox.min.js"></script>
哪些代码正在加载JS代码,这些代码根本不应该在便携式系统上加载
Which are loading JS code, that shouldn't be loaded at all on portable systems
有办法吗?
我以这种方式尝试过:
<script type="text/javascript" media="only screen and (min-width: 950px)" src="http://www.domain.com/js/jquery.min.js"></script>
但是它不起作用
提前谢谢
推荐答案
用此script标签替换您的script标签,这将创建其他三个script标签,仅窗口宽度大于一定量.
Replace your script tags with this script tag, which will create the other three script tags ONLY of the window width is larger than a certain amount.
此答案不依赖jQuery,因此您可以使用它来确定是否要加载jQuery.
This answer does not rely on jQuery, so you can use it to determine whether you want to load jQuery.
<script>
if (window.innerWidth > 500) {
var head = document.getElementsByTagName('head')[0];
var s1 = document.createElement("script");
s1.type = "text/javascript";
s1.src = "http://www.domain.com/js/jquery.min.js";
head.appendChild(s1);
var s2 = document.createElement("script");
s2.type = "text/javascript";
s2.src = "http://www.domain.com/js/jquery.colorbox.min.js";
head.appendChild(s2);
var s3 = document.createElement("script");
s3.type = "text/javascript";
s3.src = "http://www.domain.com/js/inner-code-colorbox.min.js";
head.appendChild(s3);
}
</script>
这篇关于如何根据屏幕分辨率加载或不加载JS脚本(到头部)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文