admin管理员组文章数量:1327713
So I have two different JS files to load: one for desktop and a different one for mobile. And I have used this code:
<script>
if ( $(window).width() < 739) {
<script type="text/javascript"
src=".js"></script>
}
else {
<script type="text/javascript"
src=".js"></script>
}
</script>
But the only script that loads is the desktop one.
So I have two different JS files to load: one for desktop and a different one for mobile. And I have used this code:
<script>
if ( $(window).width() < 739) {
<script type="text/javascript"
src="https://example./js-file-for-mobile.js"></script>
}
else {
<script type="text/javascript"
src="https://example./js-file-for-desktop.js"></script>
}
</script>
But the only script that loads is the desktop one.
Share Improve this question asked Sep 15, 2018 at 5:16 danskidanski 3291 gold badge6 silver badges17 bronze badges3 Answers
Reset to default 4So I found the answer:
<script>
if (screen && screen.width > 900) {
document.write('<script type="text/javascript"
src="https://example./desktop.js"><\/script>');
}
</script>
<script>
if (screen && screen.width < 900) {
document.write('<script type="text/javascript"
src="https://example./mobile.js"><\/script>');
}
</script>
Verified and working!
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
if (screen.width() < 739)
{
js.src = "js/mobile.js";
}
else
{
js.src = "js/desktop.js";
}
head.appendChild(js);
I think checking screen size to decide if its mobile or desktop browser is a little risky as it may confuse sometime with iPad or small screen desktop.
So, We can navigator to check if its mobile or desktop and den our job accordingly.
//returns true if user is using one of the following mobile browsers
var ismobile=navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i)
your e.g:
<script>
if (navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i)) {
<script type="text/javascript"
src="https://example./js-file-for-mobile.js"></script>
}
else {
<script type="text/javascript"
src="https://example./js-file-for-desktop.js"></script>
}
</script>
本文标签: javascriptLoad different JS file for mobile and desktopStack Overflow
版权声明:本文标题:javascript - Load different JS file for mobile and desktop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742228318a2436744.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论