I have my html content as
<div id="externalContent"></div>
<script src="jquery.js"></script>
<script>
console.log("the number of div elements before loading tempfile are " +$("div").length)
$('#externalContent').load('tempfile.html')
console.log("the number of div elements after loading tempfile are " + $("div").length)
$('#externalContent').append('temp.html contents loaded above...')
setTimeout(function(){
console.log("the number of div elements in page after timeout are " + $("div").length)
}, 5000)
</script>
It does simple stuff. It loads an external file, tempfile.html that has 1000 div elements using $.load, and immediately prints the number of div elements in the console.
The output is,
the number of div elements before loading tempfile are 1
the number of div elements in page after loading tempfile are 1
the number of div elements in page after timeout are 1001
So, why does the second log statement that is printed after $.load show the number of elements as one?
If dom loading (via $.load, $("...").html("blah..blah..") etc...) is an asynchronous task, how can i ensure that dom gets loaded completely?
Note: tempfile.html is a bulk file that has 1000 div elements as,
<div id="1">1</div><div id="2">2</div><div id="3">3</div>..... <div id="1000">1000</div>
.load()is indeed asynchronous. You can pass a callback function to.load(), and that will be called when loading is complete.tempfile.htmlvia an ajax call, and setting its content using$.html. does $.html load 1000 elements immediately?$.html(). If you're talking about the.html()method, then no, that's not asynchronous..load()is asynchronous because it inherently involves a network operation (the HTTP request). The.load()function is just a convenience API on top of$.ajax(). Doing your own ajax call and then using.html()is essentially what.load()does, in other words.