I am loading a series of date based URLs into an iframe to extract data from each page using a script on the top frame (same origin).
What is the best/most efficient way to wait until the iframe is ready (and and action performed) before the date loop beings loading the next item into the iframe? (with or without jQuery)
var start = new Date("01/01/2024");
var end = new Date("01/31/2024");
var loop = new Date(start);
while(loop <= end){
$("#iframe").attr("src", "data.htm?" + loop);
$("#iframe").ready(function() {
// Do something in iframe e.g. $("#iframe").contents().find("#export").click()
});
var newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
The loop doesn’t seem to wait for the iframe to load before proceeding to the next day. I assume the iframe load/ready functions only attach the functions, but do not prevent the loop loading the next page in the iframe.
2
Answers
Use
await
and a promise to wait for the next while cycle:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
You have to move your code to some asynchronous function to wait for some process to be done
And you can call this function as below: