Reputation: 329
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.com/js-file-for-mobile.js"></script>
}
else {
<script type="text/javascript"
src="https://example.com/js-file-for-desktop.js"></script>
}
</script>
But the only script that loads is the desktop one.
Upvotes: 2
Views: 5858
Reputation: 159
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.com/js-file-for-mobile.js"></script>
}
else {
<script type="text/javascript"
src="https://example.com/js-file-for-desktop.js"></script>
}
</script>
Upvotes: 0
Reputation: 329
So I found the answer:
<script>
if (screen && screen.width > 900) {
document.write('<script type="text/javascript"
src="https://example.com/desktop.js"><\/script>');
}
</script>
<script>
if (screen && screen.width < 900) {
document.write('<script type="text/javascript"
src="https://example.com/mobile.js"><\/script>');
}
</script>
Verified and working!
Upvotes: 4
Reputation: 459
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);
Upvotes: 3