Simple AJAX optimization

When ever we write an ajax code to create the AJAX objectwe tend to do it like:

function createAjaxObject()
{
if(window.XMLHttpRequest)
{
ajaxObject =  new XMLHttpRequest();
return ajaxObject;
}
else if(window.ActiveXObject)
{
ajaxObject = new ActiveXObject(”Microsoft.XMLHTTP”);
return ajaxObject;
}
else if(document.ActiveXObject)
{
ajaxObject = new ActiveXObject(”Msxml2.XMLHTTP”);
reutrn ajaxObject;
}
else
{
return null ;
}

}

Now consider a situation when we need to make large no of AJAX calls, the whole loop is called multiple times, which is not required.

So what we can write is:

function createAjaxObject()
{
if(window.XMLHttpRequest)
{
createAjaxObject = function(){ return new XMLHttpRequest(); };
}
else if(window.ActiveXObject)
{
createAjaxObject = function(){ return new ActiveXObject(”Microsoft.XMLHTTP”); };
}
else if(document.ActiveXObject)
{
createAjaxObject = function(){ return new ActiveXObject(”Msxml2.XMLHTTP”); };
}
else
{
createAjaxObject = function(){ return null ;};
}
return createAjaxObject();
}

If we do this it will rewrite the function after it is first called with the most suitable object it can handel.

Leave your response!

Be nice. Keep it clean. Stay on topic. No spam.