What is the Best way to do Browser Detection in Javascript?

前端 未结 8 1843
自闭症患者
自闭症患者 2020-12-05 16:55

In one of my Web Development classes we where asked to create a script that detects NE4,NE6+,IE4,IE6+ Browsers that display a compatable CSS script for each browser.

8条回答
  •  盖世英雄少女心
    2020-12-05 17:16

    Honestly, if you're trying to detect the browser you're attacking the wrong problem. My advice would be to detect the features that you want to use and degrade based on that. For example, if you need to create an XMLHttpRequest something similar to the following will work:

      var xhr = null;
       if (typeof(XMLHttpRequest) !== 'undefined')
          xhr = new XMLHttpRequest(...);
       else if (typeof(ActiveXObject) !== 'undefined')
          xhr = new ActiveXObject('Microsoft.XMLHTTP');
    
       if (xhr != null)
          ...do something with it
       else
          throw "No XMLHttpRequest";
    

    This approach allows your applications to grow as the browsers start to support more features. Obviously, it goes without saying that these sorts of checks should be abstracted away in a function somewhere so as not to litter your code with the same checks over and over again.

    However, if you're able to use an Ajax library like JQuery, Prototype, Dojo, YUI, etc that's probably your best bet as they already have the abstractions built in.

提交回复
热议问题