Condividi tramite


An XMLHTTPRequest tip

Over on the Ajax Blog, Dion Almaer passed on an important tip from Brent Ashley and Tim Aiello for AJAX developers – to have your cross-browser AJAX work better with IE7, you really should be invoking the native XMLHttpRequest (the cross-browser one) first to see if it’s available before instantiating the ActiveX control, instead of the other way around.

In addition to the reasons that Brent and Tim discovered, I’ve seen a bunch of code that creates the XMLHttpRequest object, uses it for a request, and then throws it away.  Obviously, this is a lot less performant than keeping the object around for multiple requests.  The native object's lifetime can be as long as that of the page. So you can reuse it like this:

            var  o = new XMLHttpRequest()
            o.open(“GET”, “data1.xml”,  true);
            o.onreadystatechange = foo();
            o.send();
            …….
            o.open(“GET”, “data2.xml”,  true);
            o.onreadystatechange=bar();
            o.send();

Xmlhttp.open has a “reset” semantic so the second open() call on the same object will abort the previous connection, disconnect previous event handler, and reset the object.

There's also a handy tool by Julien Couvreur for debugging XHTMLHTTPRequest calls for IE, or you can use Fiddler.

-Chris

Edit: Changed XMLHttpRequestObject() to XMLHttpRequest() in code illustration.

Comments

  • Anonymous
    June 08, 2006
    You would gain a lot more credibility if you used "true" instead of "TRUE".

  • Anonymous
    June 08, 2006
    Well, that's what I get for copying and pasting someone else's example.  Corrected.
    -Chris

  • Anonymous
    June 08, 2006
    if (!window.XMLHttpRequest) {
       window.XMLHttpRequest = function() {
           return new ActiveXObject("Microsoft.XMLHTTP");
       };
    }

  • Anonymous
    June 08, 2006
    The comment has been removed

  • Anonymous
    June 08, 2006
    The comment has been removed

  • Anonymous
    June 08, 2006
    Hm.

    I would agree with the proposal, if IE7's XMLHttpRequest would have the same functionality as the MSXML's version of it (see https://connect.microsoft.com/feedback/ViewFeedback.aspx?SiteID=136&FeedbackID=83800).

    Best regards, Julian

  • Anonymous
    June 08, 2006
    The comment has been removed

  • Anonymous
    June 08, 2006
    The comment has been removed

  • Anonymous
    June 08, 2006
    another one

    getTransport = function(){
     var __transport = new Array(
                                 function(){ return XMLHttpRequest ? new XMLHttpRequest() : null },
                                 function(){ return ActiveXObject  ? new ActiveXObject('Msxml2.XMLHTTP') : null },
                                 function(){ return ActiveXObject  ? new ActiveXObject('Microsoft.XMLHTTP') : null }
                                );  

     for (var i = 0; i < __transport.length; i++)
       try {
         if (__transporti)
           return __transport[i];
       } catch(e) {}

     return function(){ return null };

    }();

  • Anonymous
    June 08, 2006
    The comment has been removed

  • Anonymous
    June 08, 2006
    To people who complain about this:
    For security's sake, please, no more activex. You knew IE 7 will not allow activex run by default, your gadget won't run properly because of that, your gadget won't be able to run in other browsers.

  • Anonymous
    June 08, 2006
    lahmatiy, I don't see the benefit. Looks bloated to me ;)

  • Anonymous
    June 08, 2006
    "I’ve seen a bunch of code that creates the XMLHttpRequest object, uses it for a request, and then throws it away."

    I read the following in "The JavaScript Anthology" book by Sitepoint:
    "Even though the XMLHttpRequest object allows you to call the open method multiple times, each object can be used effectively only for one call, as the readystatechange event does not occur again once readyState changes to 4 (in Mozilla).".

    Of course in case of MS IE you really should not recreate the object again. A wrapper function or method should take care of this and many more differences between browsers.

  • Anonymous
    June 09, 2006
    @ Dao

    lahmatiy's implementation is pretty cool. It constructs a function that does not continually check the browser capabilities and will create the preferred version of the xml request object.

    It's also centralized, so all your code will get 'fixed' or updated should a new transport platform get made (such as a flex-bridge transport). Theoretically, lahmatiy could also implement a xmlhttprequest look-alike object that uses frames.

  • Anonymous
    June 09, 2006
    The comment has been removed

  • Anonymous
    June 09, 2006
    "Will there be a checkbox to disable HTTP 1.1?"

    As in Tools / Internet Options / Advanced / HTTP 1.1 Settings / Use HTTP 1.1? :)

  • Anonymous
    June 09, 2006
    " Xmlhttp.open has a “reset” semantic so the second open() call on the same object will abort the previous connection, disconnect previous event handler, and reset the object. "

    Would this mean that an abort() would be called during the new open() call??

    seems the abort(), might allow for a quick tidy-up of the pre-existing request, if it is still outstanding??

    or, a "best practices" is to call abort() manually when readyState && < 4?? then proceed to reuse the request by calling a fresh open()?

  • Anonymous
    June 09, 2006
    > lahmatiy's implementation is pretty cool. It constructs a function that does not continually check the browser capabilities and will create the preferred
    > version of the xml request object.

    As do Matthew Ratzloff's and mine implementations. They are just smaller, faster and easier to use.

  • Anonymous
    June 09, 2006
    lahmatiy's implementation looks like a copy/paste job from the prototype.js library, combining the Ajax.getTransport function with the Try.these function.

  • Anonymous
    June 09, 2006
    @Steve -
    Yes, we provided a user option to disable this.  If the user/admin does not want the old XMLHTTPRequest, they can disable it (by disabling ActiveX).  We wanted to make sure they still had the ability to disable the native version if they so chose. -Chris

  • Anonymous
    June 10, 2006
    And now that we have client-side support for XSLT in EVERY major browser (IE,Mozilla,Safari,Opera(in 9.0)) we can avoid ALL of this "if" guess work and slim down our apps to focus on access the code base that is specific to their individual ways of handling the various tasks we ask of it:

    http://www.xsltblog.com/archives/2005/12/finally_someone_1.html

  • Anonymous
    June 10, 2006
    The comment has been removed

  • Anonymous
    June 11, 2006
    @ nomad513
    Yes, you are right, implementation looks like some functions from the prototype.js library. But this library don't optimized and:
    1. do selection of transport constructor every time while create Ajax.Request object
    2. instead of native XMLHttpRequest it's use ActiveX
    Anyway, you couldn't write something really new :) I'm just want to show implemetation looks more pretty than using conditional comments.

  • Anonymous
    June 12, 2006
    The comment has been removed

  • Anonymous
    June 12, 2006
    In general, almost all new IE features have an option to control whether or not the feature is enabled.  

    Say a company decides that they don't want XMLHTTP available on their network for some reason (and rest assured, companies want all sorts of "interesting" things).  

    Now, in the old days, you could simply disable the object or disable ActiveX. Since we've added a native implementation, some company is going to ask for a way to disable that too.  So we've added one.  

    We don't expect that any normal user is likely to uncheck this, and in fact, very few users will even see the option at all.  

    (And to be clear, there's nothing wrong with the ActiveX version of XMLHTTP; the window-Native version has been added for simplicity in developing AJAX sites).

  • Anonymous
    June 12, 2006
    I think this may be a little out of place but I think its worth informing:

    IE6 crashes when vml is fetched using XMLHTTP and shown using objDiv.innerHTML = objXMLHTTP.reponseText.

    The event log says:
    Faulting application IEXPLORE.EXE, version 6.0.3790.1830, faulting module vgx.dll, version 6.0.3790.1830, fault address 0x000ab694.

    I know that MS has released a fix to this issue for WinXP SP2 systems (KB Article ID: 885932).
    But I would just like to point out that this occurs often on Windows Server 2003 + SP1 too.

    Any ideas when can we get a patch for this?

  • Anonymous
    June 14, 2006
    What about DOMParser, XMLSerializer, document.implementation.createDocument etc? Without those we will continue to rely on ActiveX being turned on to achieve the same things.

    As far as I know Dave Massey promised that these would be added as well. However, it seems that marketing and not real world need has been driving IE7 features when it comes to the APIs.

  • Anonymous
    June 14, 2006
    > I'm just want to show implemetation looks more pretty than using conditional comments.

    You can leave out the conditional compilation thing if you don't like it (see Matthew Ratzloff's code.)

    Three lines of code making new XMLHttpRequest; functional in IE 5.5 and 6. How's what you've posted prettier?

  • Anonymous
    June 17, 2006
    @Erik-- Dave made no such promise for IE7.  He did promise that we'd add them to our list for consideration in a future release.

    I'm not sure where you got the notion that marketing had anything to do with this.

  • Anonymous
    October 15, 2006
    PingBack from http://lorelle.wordpress.com/2006/10/16/are-wordpress-themes-and-plugins-ready-for-internet-explorer-7/

  • Anonymous
    October 27, 2006
    PingBack from http://w3net.sytes.net/blog/?p=5

  • Anonymous
    November 17, 2006
    PingBack from http://blog.15minutesmedia.com/?p=13

  • Anonymous
    December 17, 2006
    这一年多来Vista有不少版本都在我机器上借宿过,从早期巨慢无比到beta1时我的显卡也能跑Aero了.现在RTMBusiness版也占据了我的硬盘的一部分。但是无论什么时候,总是感觉在Vista上...

  • Anonymous
    September 30, 2007
    PingBack from http://blog.needtip.com/?p=13

  • Anonymous
    September 30, 2007
    PingBack from http://blog.needtip.com/?p=15

  • Anonymous
    September 30, 2007
    PingBack from http://blog.needtip.com/?p=19

  • Anonymous
    September 30, 2007
    PingBack from http://blog.needtip.com/?p=28

  • Anonymous
    September 30, 2007
    PingBack from http://blog.needtip.com/?p=26

  • Anonymous
    October 11, 2007
    PingBack from http://blog.needtip.com/?p=43

  • Anonymous
    October 11, 2007
    PingBack from http://blog.needtip.com/?p=42

  • Anonymous
    October 11, 2007
    PingBack from http://blog.needtip.com/?p=49

  • Anonymous
    October 11, 2007
    PingBack from http://blog.needtip.com/?p=52

  • Anonymous
    October 11, 2007
    PingBack from http://blog.needtip.com/?p=50

  • Anonymous
    October 11, 2007
    PingBack from http://blog.needtip.com/?p=38

  • Anonymous
    October 11, 2007
    PingBack from http://blog.needtip.com/?p=65

  • Anonymous
    October 14, 2007
    PingBack from http://blog.needtip.com/?p=87

  • Anonymous
    October 14, 2007
    PingBack from http://blog.needtip.com/?p=88

  • Anonymous
    October 30, 2007
    PingBack from http://discount-perfume-hq.com/?p=1820

  • Anonymous
    October 31, 2007
    PingBack from http://discount-perfume-hq.com/?p=2720

  • Anonymous
    October 31, 2007
    PingBack from http://blog.needtip.com/tips/features-brief-summaries-of-major-theories-of-learning/

  • Anonymous
    October 31, 2007
    PingBack from http://blog.needtip.com/tips/theinfopro-tip-is-an-independent-research-network-and-2/

  • Anonymous
    October 31, 2007
    PingBack from http://blog.needtip.com/tips/altavista-provides-the-most-comprehensive-search-experience-on/

  • Anonymous
    October 31, 2007
    PingBack from http://blog.needtip.com/tips/linux-tipnet-home-2/

  • Anonymous
    October 31, 2007
    PingBack from http://blog.needtip.com/tips/tip-get-an-etf-quote-for-ishares/

  • Anonymous
    October 31, 2007
    PingBack from http://blog.needtip.com/tips/two-at-the-tip-chicagotribunecom/

  • Anonymous
    October 31, 2007
    PingBack from http://blog.needtip.com/tips/tip-community-page-where-all-media-tagged-tip-2/

  • Anonymous
    November 08, 2007
    PingBack from http://blog.needtip.com/tips/got-you-down-in-just-45-minutes-tip/

  • Anonymous
    November 08, 2007
    PingBack from http://blog.needtip.com/tips/tip-ex-sports-betting-and-odds-comparison-service-for-gamblers/

  • Anonymous
    November 08, 2007
    PingBack from http://blog.needtip.com/tips/mac-tip-display-the-date-on-the-menubar/

  • Anonymous
    June 08, 2009
    PingBack from http://toenailfungusite.info/story.php?id=1406

  • Anonymous
    June 15, 2009
    PingBack from http://mydebtconsolidator.info/story.php?id=18708

  • Anonymous
    June 15, 2009
    PingBack from http://einternetmarketingtools.info/story.php?id=21568