1

I created a website for big (Desktop) and small (Mobile) devices. Not only the .css files differ each other but also the .js files in which the animations are saved. My Problem now is, I don't know how to make the browser use the .js file for small devices if the display is small and on the other site the .js file for big devices if the display is big. Is there any possible solution to use only one webspace with two Java Script files automatically choosen by screen size?

2
  • So you want the browser to use a particular js file depending on the screen size? Commented Apr 11, 2015 at 22:02
  • That's what it sounds like. Commented Apr 11, 2015 at 22:02

5 Answers 5

2

Using JQuery you can do something like this:

if ( $(window).width() > 739) {      
  //Add your javascript for large screens here 
} 
else {
  //Add your javascript for small screens here 
}

This way you only require one JS file.

Sign up to request clarification or add additional context in comments.

Comments

1

i am not sure it is good way or not, but you can also use simple javascript to detect the mobile browser

<script>
if( /Android|iPhone|iPad|BlackBerry|IEMobile/i.test(navigator.userAgent) ) {
 // include mobile
} 
else {
//include desktop
}
</script>

Comments

0

Here you go:

if (screen.width > 768) {
    //keep your desktop js here
}

if (screen.width < 769) {
    //keep your mobile js here
}

Comments

0

You can dynamically load a JavaScript file after checking the window size using:

var file = window.innerWidth < 800 ? 'small.js' : 'big.js'
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file);

Comments

0

Testing the user agent is more robust than testing the window width. Here's a library than can help you: WURFL.io

Just grab the lib to your page and add:

if (WURFL.is_mobile) {
    //add mobiles scripts
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.