开发者

Javascript xmlHttpRequest object detection vs try..catch

开发者 https://www.devze.com 2023-03-15 13:48 出处:网络
When checking whether a particular browser supports AJAX, object detection is what I usually do: if (window.XMLHttpRequest)

When checking whether a particular browser supports AJAX, object detection is what I usually do:

if (window.XMLHttpRequest) 
{ 
    xhr = new XMLHttpRequest(开发者_StackOverflow社区);
} 
else if (window.ActiveXObject)
{
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

However whenever I take a look at codes written by the developers who are more senior, it is more likely that I would see a try-catch block instead:

try {
   xhr = new ActiveXObject("Microsoft.XMLHTTP");    //IE 
}
catch(e)    // if not IE
{
  xhr = new XMLHttpRequest(); 
}

I know that some people say try..catch is slower, however if this is pretty much only a matter of preference, is there a convention/more "standard" way to do this? I was also in the same situation long time ago when I was deciding between innerHTML(not standard) vs DOM(standard). Thank you for your time. Any suggestion would be appreciated.


How about xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");

XMLHttpRequest is preferred if it fails, it uses ActiveXObject("Microsoft.XMLHTTP"). Much more elegant and dry.

0

精彩评论

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