To wait for the dom content to be loaded before executing JavaScript, use this callback:
window.addEventListener('DOMContentLoaded', (event) => { console.log('DOM fully loaded and parsed'); });
Window: DOMContentLoaded event