Replace script if viewed in IE9?

别说谁变了你拦得住时间么 提交于 2019-12-10 15:19:46

问题


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.


回答1:


You can use conditional comments 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.




回答2:


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 comments but they are only recognized by IE.

-- Pavel




回答3:


You can use conditional comments 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.com/how-to-create-an-ie-only-stylesheet/




回答4:


May i recommend 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.



来源:https://stackoverflow.com/questions/4605894/replace-script-if-viewed-in-ie9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!