2

Does jQuery create a script node in the DOM setting the source equal to the request and then remove the script node?

I was debugging it in firebug and I never noticed an any extra script nodes ever being added. Wondering how jQuery handles this?

E.g.

$(document).ready(
    function(){
        $.ajax({
          url: "...",
          type: 'GET',
          dataType: 'jsonp'
        });
    }
);
user17753
  • 3,083
  • 9
  • 35
  • 73

2 Answers2

1

Yes, jQuery creates a script element in the DOM. (This is the only way that JSON-P can work.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Is it removed, though? e.g. if I make many such JSONP calls will the DOM be flooded with all those script nodes? – user17753 Oct 17 '12 at 13:47
  • @user17753: I'd be shocked if it left them lying around. jQuery's source is convoluted and hard to read in this area, but it should be trivial to find out: Do three or four JSON-P calls and then look at the DOM in Chrome Tools or Firebug or whatever you use. – T.J. Crowder Oct 17 '12 at 13:49
  • Yea, as I originally said in the question, I never noticed any being added/removed. – user17753 Oct 17 '12 at 13:50
  • @user17753: They're definitely added (again, otherwise JSON-P just wouldn't work), but if they're removed (and I'm sure they are), it would naturally happen fairly quickly (e.g., as soon as the JSON-P script loaded). – T.J. Crowder Oct 17 '12 at 13:51
  • Ok so, I'd assume that somehow it passes the callback function to another function that executes the callback, and then executes another function (right after) to remove the `script` node from the DOM. – user17753 Oct 17 '12 at 13:59
  • @user17753: Or it might remove the node first (since that would have no effect on the code loaded by the node), but yeah, that's almost certainly what it's doing. – T.J. Crowder Oct 17 '12 at 15:53
1

Take a look at the source of the jQuery.ajaxTransport function in the jQuery source. it returns an object with a send element containing a function that adds the script to the DOM. This script element has an onload and onreadystate change handler that removes itself from the DOM.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Yea, I see on [this question](http://stackoverflow.com/questions/1929742/can-script-readystate-be-trusted-to-detect-the-end-of-dynamic-script-loading) both of those have to be set due to browser inconsistencies. – user17753 Oct 17 '12 at 14:08
  • Also, I'm guessing I didn't see the `script` nodes being added to the DOM because it was happening very, very quickly that they were being added and then removed. I do see that the script was loaded, though. – user17753 Oct 17 '12 at 14:09