- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Conditional Script Loading
Hi,
I would like to know that if there is a way to load a particular script file on desktop but not loading on mobile phones using modernizer?
For example.
<script src="js/script1.js"></script>
<script src="js/script2.js"></script>
<script src="js/script3.js"></script>
Scripts 1,2 and 3 are loading on desktop but I don’t want to load script 2 and script 3 on mobile phones( as I am not using them).
Thanks.
<script>
function isMobileDevice(){
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
return true;
}
else {
return false;
}
}
</script>
This function will return true if it detects a mobile device, and false otherwise.
Then in script2.js and script3.js simply wrap all of your code that you do not want to execute in:
<script>
if (!isMobileDevice()){
//…..
}
</script>
If you do not want to load the file altogether, here’s a stack answer about this question.
http://stackoverflow.com/a/15521523
Simply conditionally build a script tag in javascript based on the outcome of isMobileDevice() and append it to wherever you put your scripts.
Shikkediel, that was my first thought as well, but kwerty specifically said “mobile phones”. Simply doing a screen size check will not load the js files on a desktop browser if scaled below, say 500px (normal px width to check for), as you probably already know. I guess it really depends on what they’re trying to do. That’s the only reason I suggested browser sniffing. Otherwise, yeah, it’s much easier to just check screen size.
Couldn’t agree more. +1