I have a question about inserting html with JavaScript into the DOM after an Ajax call using JQuery’s .load().
Assume the following sample html section:
<script>$(document).ready(function(){var e = $('#'+'@Servergenerated');})</script>
<div id='@Servergenerated'>Test Element</div>
If I return the above section through an Ajax call and insert the result into the DOM using JQuery’s load() function — Will both the markup rendering and the script execute as a blocking call?
Meaning, since .load() executes on the single thread available to JavaScript, will it ensure that both the markup rendering and the JavaScript execution will finish before other JavaScript on the same main page can be invoked ?
The Ajax request is initiated through $("#someElement").load(..)
In the above case, can I always assume that the JS is always paired up with the correct html (so that the JS will execute against the ID that is currently defined on the page)
However, is there a difference between using .load() and .html().
Typically I use $.get to retrieve the data and then insert it into the DOM using .html(). This code is however in a third party library and it’s uisng .load() instead..
When you use
$().load(url,fn), code that follows that line will execute before the html is appended to the page because$().load(url,fn)performs an asynchronous http request to get the content. See examples at end.Another important thing to remember is that with
$().load(url,fn), if the html returned contains javascript, that javascript may execute before the content exists on the page resulting in plugins not being initialized properly. This is why it is strongly suggested that you should not use$().load(url,fn)to bring in content that contains scripts.Examples:
In the above example, logs 1 2 and 3 are garunteed to happen in that order, however 4 and 5 may swap positions depending on which ajax request completes the fastest. There is no way of avoiding that other than not using
$().load(url,fn)or requesting div2’s content in the success of requesting div1’s content.