最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace script if viewed in IE9? - Stack Overflow

programmeradmin1浏览0评论

How easy would it be to run a different javascript depending on the user browser?

For example if someone visits the site with IE9 I would like it to run a different script to the one it would run normally for Chrome users.

How easy would it be to run a different javascript depending on the user browser?

For example if someone visits the site with IE9 I would like it to run a different script to the one it would run normally for Chrome users.

Share Improve this question asked Jan 5, 2011 at 15:37 Vince PVince P 1,7917 gold badges30 silver badges67 bronze badges 1
  • 1 why? there is probably a better way. – David Murdoch Commented Jan 5, 2011 at 15:43
Add a ment  | 

4 Answers 4

Reset to default 4

You can use conditional ments for this:

<!--[if lte IE 6]>
    <script>alert('lte stands for less than or equal to')</script>
<![endif]-->

<!--[if lt IE 7]>
    <script>alert('lt stands for less than')</script>
<![endif]-->

<!--[if gte IE 9]>
    <script>alert('gte stands for greater than or equal to')</script>
<![endif]-->

etc.

There are various browser detection techniques. You can try detecting the browser (by yourself by examining the navigator.userAgent property) or you can use methods available in almost every Javascript framework. For example:

  1. jQuery.browser
  2. Detecting browser with Prototype JS

Alternatively you can use conditional ments but they are only recognized by IE.

-- Pavel

You can use conditional ments in the HTML.

<!--[if IE]>
   <script src="ie_only.js"></script>
<![endif]-->

This can also be used for external stylesheets

more info on this post http://css-tricks./how-to-create-an-ie-only-stylesheet/

May i remend feature detection instead.

if (someIEAPI) {
    // ie code
} else if (someChromeAPI) {
    // chrome code
}

This code is more robust and if firefox or opera supports one of the API's you don't have to check for their browsers anyway.

Besides browsers have a habit of lying to you and pretending to be whatever is hip.

发布评论

评论列表(0)

  1. 暂无评论