I have issues with jquery code in $(document).ready(function () {…}); sometimes not being executed when the page is loading.
How can I force the function to be executed? Or force the code to await for the function to be finished if it is related to async issues?
<!DOCTYPE html>
<html>
<head>
<link rel='icon' href='images/favicon.ico' type='image/x-icon'/ >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var fileReading = new Array();
$.get('output.txt', function(data){
fileReading = data.split(',');
fileReadingLength = fileReading.length-1;
});
$(document).ready(function () {
$("#img1").attr({ "src": fileReading[fileReadingLength-1] });
$("#img2").attr({ "src": fileReading[1] });
$("fileReadingLength").text(fileReadingLength);
for (i = 0; i <= fileReadingLength; i++) {
$('body').append('<br><img id="img"'+i+' src="'+fileReading[i]+'">')
}
});
</script>
</head>
<body>
Number of images: <fileReadingLength></fileReadingLength> <br>
</body>
</html>
2
Answers
My understanding is that since your
.get
is done asynchronously, for large files,$(document).ready
fires beforefileReading
has elements. Why not move the$(document).ready
into the.get
, this is guaranteed to fire even if it’s set after the document is ready.Note:
$(document).ready(handler)
has been deprecated in favour of$(handler)
since jQuery 3.0.The reason why it doesn’t work sometime is because
$.get
is asynchronous. If the document is ready before the$.get
block returns a response, then you will have no values for bothfileReading
andfileReadingLength
.Therefore, the solution is to actually abstract all that DOM modification/updating logic into a function, which you then invoke once the
$.get
promise is resolved: