In my webpage, I have some HTML elements and some JavaScript functions that act on them. I want my HTML elements to be fully loaded before JavaScript functions run.
For example, I have <div id="buttonsection"></id>
. I want buttonsection div to load first before my updateButtonSection() run.
At first, I was doing this by using timeout:
setTimeout("updateButtonSection()", 1500);
However, if timeout is too short, the updateButtonSection will run before buttonsection div finish loading. But if timeout is too long, users with good internet speed will have not have a good experience since users have to wait on the timeout.
So then I decided to check if div is loaded before running the JavaScript function.
function updateMarkerButton(){
//if elements not loaded, wait 1 second and then call itself
if(document.getElementById('buttonsection') === null ){
setTimeout("updateMarkerButton()", 1000);
}else{
....
}
This mostly works until I find out if I am already on the webpage with everything loaded, if I call my refresh function, then updateMarkerButton will run immediately because the current buttonsection div is already loaded so document.getElementById('buttonsection') is not null; thus updateMarkerButton will not wait for buttonsection div to reload before it runs.
Any suggestion on how else I can prevent this racing condition so JavaScript functions only run after HTML elements finish loading?