开发者

Loading stylesheet dependant on User Agent

开发者 https://www.devze.com 2023-03-22 15:57 出处:网络
I have to load a different Stylesheet depending on whether the User Agent is an iPad or other.I know that generally, detecting browsers isn\'t the most fantastic idea and will probably cripple our mai

I have to load a different Stylesheet depending on whether the User Agent is an iPad or other. I know that generally, detecting browsers isn't the most fantastic idea and will probably cripple our maintainability sometime in the future..not my decision.

So here we have some JavaScript to detect the user agent. It isn't working. I may have mis-escaped something. The error I am getting is a red herring (object reference), but only shows up when I execute the JavaScript.

    $(document).ready(function () {
        alert('ready fired');
        if (navigator.userAgent.indexOf("iPad") != -1) {
            //alert('bleep bloop blop...iPad detected');
            var stringToWrite = '<script src=\'\<\%\= ResolveUrl("~/Scripts/iscroll.js") \%\>\' type="text/javascript"><\/script>';
            stringToWrite += '<link href=\'\<\%\= ResolveUrl("~/Stylesheets/scrollbar.css") \%\>\' rel="stylesheet" type="text/css" \/>';
            stringToWrite += '<link href=\'\<\%\= ResolveUrl("~/Stylesheets/iPadCommon.css") \%\>\' rel="stylesheet" type="text/css" \/>';
            alert(s开发者_如何学PythontringToWrite);
            document.write(stringToWrite);
        }
        //else
        //alert('bleep bloop blop...who cares browser');
    });


found this at random on the internet:

//returns true if user is using one of the following mobile browsers
var ismobile=navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i)

http://www.javascriptkit.com/javatutors/navigator.shtml


You probably should consider detecting the agent on the server side, otherwise it won't work for browsers which have javascript disabled.


If possible you should use @media handheld to use style rules specific to handheld devices.

If that it too course, i.e. if you need different CSS for iPad vs. iPhone vs. Android, you should do a server-side detect and add CSS classes to the <html> and/or <body> tags, like

<html class="android">

or

<body class="iOS">

Quentin's comment is right - trying to write a server-side meta-tag <%= ResolveUrl(etc) %> will not work because the server isn't running what the javascript writes. The server is finished with its processing already.

0

精彩评论

暂无评论...
验证码 换一张
取 消