Skip to content
The Chat Archive
claude-sonnet-4-20250514· Anthropic LMArena Human Preference 140K

how to avoid missing domcontentloaded event in an async script js?

  1. User

    how to avoid missing domcontentloaded event in an async script js?

  2. Assistant

    The main issue with async scripts and DOMContentLoaded is that async scripts can load and execute after the DOM is already parsed, meaning the DOMContentLoaded event 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.readyState first. If it's 'loading', the DOM isn't ready yet and you can safely listen for DOMContentLoaded. If it's 'interactive' or 'complete', the DOM is already parsed and you can execute your code immediately.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.