// 普通函数
function createXHR(){
var xhr = null;
try{
// Firefox,Opera 8.0+,Safari,IE7+
xhr = new XMLHttpRequest();
}catch(e){
// Internet Exporler
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xhr = null;
}
}
}
return xhr;
}
// 惰性函数
// 第二次生效
function createXHR(){
var xhr = null;
if(typeof XMLHttpRequest != 'undefined'){
xhr = new XMLHttpRequest();
createXHR = function(){
return new XMLHttpRequest();
}
}else{
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
createXHR = function(){
return new ActiveXObject("Msxml2.XMLHTTP");
}
}catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
createXHR = function(){
return new ActiveXObject("<icrosoft.XMLHTTP");
}
}catch(e){
createXHR = function(){
return null;
}
}
}
}
return xhr;
}
javascript惰性载入函数
最新推荐文章于 2021-10-21 17:26:54 发布
本文介绍了一种创建XMLHttpRequest对象的方法,并通过惰性函数实现了浏览器兼容性和代码的优化。该方法首先尝试使用XMLHttpRequest对象,如果不可用,则尝试使用不同的ActiveX对象来创建跨浏览器的AJAX请求。
610

被折叠的 条评论
为什么被折叠?



