Search code examples
javascriptdomjsonp

JSONP in Javascript: remove script DOM element immediately


There is something I don't understand in the DOM/Javascript flow in the following classical function which builds a script DOM element dynamically in order to have a JSONP request served within this injected script:

function requestServerCall(url) { //Construct the script tag at Runtime  
  var head = document.head;  
  var script = document.createElement("script");  
  script.setAttribute("src", url);  
  head.appendChild(script);  
  head.removeChild(script); // remove the script tag once inserted to avoid memory consumption  
}  

What I don't get is: this function immediately removes the script child from the DOM. Does it means the function hangs when appending the child? I think not. So it means the DOM will sort of remember to remove the child after the insertion of it has been fulfilled through the HTTP request of the injected url.

Intuitively, I would think this is the call-back's job (call-back embedded in the url in this example) to destroy the script (or a timer call-back as we have no guarantee call back will be ever called in case of failure).

Can someone elaborate on the Javascript/DOM execution flow which justifies this 'early' child removal in the DOM?


Solution

  • Adding the script element to the DOM immediately tells the browser to fetch the script and, once it's fetched, execute it. appendChild does not block while that happens.

    The browser doesn't "remember" to do the removeChild later, it does it right away. But removing the script element from the DOM does nothing to stop the process of fetching and running the script; it's already been started.

    So adding and removing right away is fine.

    Being a bit paranoid, I'd always test on my target browsers, just in case of implementation oddities.