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>