Will the script tag be added to the element running before the next line after .append ()?

I am extracting an HTML document from the server, storing it in the data variable, and then adding it to the <ul> element on the page. Here is what data looks like:

 <script> hasNext = true // global variable </script> <li class="result">one</li> <li class="result">two</li> 

Then in my main Javascript for the page, I do this:

 ulElement.append(data); if (hasNext) { ulElement.append(nextPageButton); } 

This seems to work, but I just wanted to make sure that the code in the <script> tag will always work before my if . And I could not find information about this possible race condition on the Internet. Thoughts?

+5
source share
2 answers

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 // global variable </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.

+1
source

If you really want to do this, perhaps you can wait for the page to load using window.onload.

 ulElement.append(data); $(function(){ if (hasNext) { ulElement.append(nextPageButton); } }); 
0
source

Source: https://habr.com/ru/post/1232631/


All Articles