bugmagnet
bugmagnet

Reputation: 7769

When does a synthetic javascript element get executed?

Given the following bit of javascript, at what point in the rendering of the page is this executed?

Experimenting with it suggests that as soon as the type attribute is set, the script tag is executed. Is this actually the case? Or is it executed once the whole page has downloaded and rendered?

And where in the DOM does N fall once declared? At the beginning, middle or end?

N = document.createElement('script');
N.setAttribute('src', 'http://localhost/traffic.php' +
    '?_Cookie=' + escape( document.cookie ) +
    '&_Referrer=' + escape( document.referrer ) +
    '&_Href=' + escape( window.location.href ) );
N.setAttribute('type', 'text/javascript' ); 

Extra Info

The original script had

_Noose = document.getElementById('Noose');

at the beginning and

O = _Noose.parentNode.replaceChild( N, _Noose );

at the end.

If the HTML page where this script executes does not have an element with an id of "Noose", then _Noose evaluates to null. Will the script fail or succeed? It appears to be succeeding.

Upvotes: 1

Views: 104

Answers (2)

st-boost
st-boost

Reputation: 1907

Solidarity answer.

If by executed you mean that the page on the client's computer runs the code at the url linked to by the script element, then your example code does not execute. A script tag will not execute until it is appended to the DOM manually. This also answers where it is appended (wherever you put it), and in what context it is executed (the window you append it to).

If you are asking when the browser requests the url that you set as the script's source, then it is requested after it is set, but it doesn't do anything with the fetched code until the script element is appended to the DOM. If it looks like the url is being loaded after you set the type, that is because each page in a browser is largely single-threaded - the browser has to finish executing your code before it can check its queue and realize it should request the script's url. (This is also why you never want to execute javascript in the document's head.)

Upvotes: 1

Nick Clark
Nick Clark

Reputation: 4467

Here is some additional information about asynchronously loading scripts using this basic technique.

http://unixpapa.com/js/dyna.html

You can use the developer console in Chrome or Firebug to see when the request is being made. Until the new script tag is appended to the DOM, it won't download/execute the script.

Upvotes: 1

Related Questions