仅为平板电脑和智能手机添加和加载Jquery移动脚本

时间:2013-02-13 19:57:52

标签: jquery jquery-mobile responsive-design

如果用户使用智能手机/平板电脑或笔记本电脑,我想加载不同的脚本。

这是我想要的结果:

笔记本:

<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 

智能手机和平板电脑

<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>

我该怎么做?

1 个答案:

答案 0 :(得分:7)

您正在寻找嗅探用户代理以检测特定设备,或者您可以使用浏览器/屏幕宽度来确定您的用户属于哪个类别。

要根据浏览器宽度添加脚本,您可以执行以下操作:

<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>

但这有几点需要注意。

  1. 小型桌面浏览器可以<=1024px宽,因此平板电脑和桌面用户之间会有一些重叠。
  2. 需要在您的Web服务器上托管JS / CSS,以便您可以在不出现跨域策略问题的情况下访问它们。
  3. 无论您如何检测移动设备/平板电脑设备,CSS / JS包含都很适合您。有一些脚本可以检测运行服务器端和客户端的设备,快速的Google搜索会调出许多这些脚本。我没有使用过这些脚本,所以我无法提供很多关于它们用法的指导。

相关问题