Regardless of whether this is a good idea ....
For the browser to interpret the dynamically inserted DOM, it must parse the content that you provide. This is a synchronous process (if your JS does not execute any AJAX requests, setTimeouts , etc.). From the Google Dev blog :
When the HTML parser encounters a script tag, it pauses the process of building the DOM and controlling the JavaScript engine; as soon as the JavaScript engine completes, the browser then rises from where it left off and resumes the DOM construct.
This means that the browser will be guaranteed to process and run JS in the script tag (and also add the DOM to the string) before it moves on to the next JS command: if (hasNext) {...
In your example, it doesn't matter where the <script> was associated with the rest of the dynamically inserted DOM in data , because there is no dependency between the DOM and this script. While it is in data , the browser will process these commands before moving to the line after append . For instance. it will work just as well
<li class="result">one</li> <li class="result">two</li> <script> hasNext = true </script>
Since your code checks the dynamically "entered" variable after calling append , the variable ( hasNext ) will be guaranteed (as long as it is in the <script> in data ).
For instance:
$( ".test" ).append( "<p>Test</p><script>var globalVariable = 123;" ); $( ".test" ).append( globalVariable );
will write:
<p>Test</p>123
The most likely condition for the race is the interaction with some servers that does not indicate the hasNext variable, in which case the code will either use false for this variable:
if (undefined) { alert('I won\'t be called'); } else { alert('I will be called'); }
-OR, the more risky version
your if (hasNext) { ... } will use the previous value of this variable from the previous call to append with different data . This is quite risky and perhaps the best reason to avoid this approach.