Add and load the Jquery mobile script only for tablets and smartphones
You're looking at either sniffing the User-Agent to detect for specific devices or you can use the browser/screen width to determine which category your user falls under.
To add scripts based on browser width you can do something like this:
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
(function ($) {
//check if the browser width is less than or equal to the large dimension of an iPad
if ($(window).width() <= 1024) {
//create an AJAX request for the CSS file
$.ajax({
url : 'jquery.mobile-1.2.0.min.css',
success : function (response) {
$('head').append('<style>' + response + '</style>');
}
});
//create an AJAX request for the JS file, setting the dataType to 'script' will have jQuery automatically evaluate the JS code in the global scope
$.ajax({
url : 'jquery.mobile-1.2.0.min.js',
dataType : 'script'
});
}
})(jQuery);
</script>
This has a few caveats though.
- Small desktop browsers can be
<=1024px
wide so you'll have some overlap between tablet and desktop users. - The JS/CSS needs to be hosted on your web server so you can access them without Cross-Domain-Policy issues.
The CSS/JS inclusion will most likely work for you no matter how you detect mobile/tablet devices. There are scripts out there to detect devices that run server-side as well as client-side, a quick Google search will bring up many of these scripts. I have not used these scripts however so I can't offer much guidance on their usage.
Related videos on Youtube
Romain
Updated on September 16, 2022Comments
-
Romain over 1 year
I would like to load different scripts if the user is on a smartphones/tablets or on a laptop.
Here is the result that I want :
Laptop:
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
smartphones and tablets
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
How can I do it?
-
xarlymg89 almost 6 yearsIMHO this isn't a good option, specially now a days that there are smartphones with screens wider than 1024px.
-
Jasper almost 6 years@CarlosAlbertoMartínezGadea Hi Carlos. The pixel width of a device screen doesn't necessarily correlate to the viewport width of the browser on that device. E.g. an iPhone X has a screen width of 1125px but the viewport is 375px. This website has a nice list of device viewport sizes: mediag.com/news/popular-screen-resolutions-designing-for-all.
-
xarlymg89 almost 6 yearsI'll check on that, although at the end I have opted to use an option that checks the user agent. Thanks anyway :)