how to avoid missing domcontentloaded event in an async script js?
- User
how to avoid missing domcontentloaded event in an async script js?
- Assistant
The main issue with async scripts and
DOMContentLoadedis that async scripts can load and execute after the DOM is already parsed, meaning theDOMContentLoadedevent may have already fired.Here are several reliable approaches:
1. Check document.readyState first:
function onDOMReady(callback) { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', callback); } else { // DOM is already ready callback(); } } // Usage onDOMReady(() => { // Your code here });2. Use a combined approach:
function whenReady(callback) { if (document.readyState !== 'loading') { callback(); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', callback); } else { // Fallback for older browsers document.attachEvent('onreadystatechange', function() { if (document.readyState === 'complete') callback(); }); } }3. Modern Promise-based approach:
const domReady = new Promise(resolve => { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', resolve); } else { resolve(); } }); // Usage domReady.then(() => { // Your code here }); // Or with async/await async function init() { await domReady; // Your code here }4. Simple one-liner utility:
const ready = (fn) => document.readyState !== 'loading' ? fn() : document.addEventListener('DOMContentLoaded', fn); // Usage ready(() => { // Your code here });The key insight is checking
document.readyStatefirst. If it's'loading', the DOM isn't ready yet and you can safely listen forDOMContentLoaded. If it's'interactive'or'complete', the DOM is already parsed and you can execute your code immediately.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.