why can't I see the script tag injected by jquery in jsonp request?

154 Views Asked by At

I am familiar with JSONP and how it works, but I'm noticing something confusing.

When using jquery's $.ajax method with a datatype of "jsonp" Every account I have read suggests that jquery will inject a script tag into the dom to issue the request.

My code works (on my bare bones test page), but when I inspect with Chrome Dev Tools I'm not seeing any injected script tag. What gives?

$.ajax({

    url: "https://status.github.com/api/status.json",

    dataType: "jsonp",

    type: "GET",

    success: function( response ) {
        console.log( response ); // successfully logs data from github
    }

});

When looking at the network tab, this is the url jquery requests:

https://status.github.com/api/status.json?callback=jQuery2130779439534759149_1434721871588&_=1434721871589

Also, where does jquery put this function?

function jQuery2130779439534759149_1434721871588(){
   // my success callback I presume
}
2

There are 2 best solutions below

0
On BEST ANSWER

This is what I read on the web (and noted down for my ref) a while ago. What jQuery does is it adds script tag to the DOM only until the callback (success function) is done executing. The tag is added to the header. It also adds a function to the window object which is called on return.

jQuery2130779439534759149_1434721871588 is just an object living on the window object and is a dynamically added function. When the function is done executing, it will remove itself from the window object.

The callback related function (from minified jQuery source) looks like the following.

function(q){n=q;b();d();z[i]=v;try{delete z[i]}catch(p){}A&&A.removeChild(B)}

Hope that helps.

0
On

It actually gets added and then removed - If you inspect your DOM - Especially in cases of recursive calls - You will see DOM Highlights (In Chrome Dev Tools) - whenever a call is made - You can observe that the <Script..> tag is added and removed after execution.