javascript - Will a script tag appended to an element run before the next line after .append()? -
i'm fetching html document server, storing in variable data
, appending <ul>
element on page. here data
looks like:
<script> hasnext = true // global variable </script> <li class="result">one</li> <li class="result">two</li>
then in main javascript page, this:
ulelement.append(data); if (hasnext) { ulelement.append(nextpagebutton); }
it seems work, wanted make sure code in <script>
tag run before if
statement. , couldn't find info on possible race condition online. thoughts?
independent of whether or not idea....
in order browser interpret dynamically inserted dom, has parse content providing. synchronous process (assuming js doesn't ajax requests, settimeouts
etc). google dev blog:
when html parser encounters script tag, pauses process of constructing dom , yields control on javascript engine; once javascript engine has finished running, browser picks left off , resumes dom construction.
this means browser guaranteed process , execute js in script tag (as add dom in string) before moves onto next js command: if (hasnext) {...
.
in example wouldn't matter <script>
tag in relation rest of dynamically inserted dom in data
because there no dependency between dom , script. long in data
, browser process commands before proceeding line after append
. e.g. work well
<li class="result">one</li> <li class="result">two</li> <script> hasnext = true // global variable </script>
since code checking dynamically 'injected' variable after append
call, variable (hasnext
) guaranteed exist (as long in <script>
tag in data
).
for example:
$( ".test" ).append( "<p>test</p><script>var globalvariable = 123;" ); $( ".test" ).append( globalvariable );
will write:
<p>test</p>123
the race condition server interaction not specifying hasnext
variable, in case code either use falsey value of variable:
if (undefined) { alert('i won\'t called'); } else { alert('i called'); }
-or, more risky version-
your if (hasnext) { ... }
use previous value of variable prior call append
different data
. quite risky , possibly best reason avoiding approach.
Comments
Post a Comment