JavaScript

DOM Ready Helper

by @admin
9h ago
Apr 28, 2026
Public
Runs a callback when the DOM is fully parsed and ready, without waiting for images or stylesheets. Works whether called before or after DOMContentLoaded has already fired — unlike a bare addEventListener which misses the event if the DOM is already ready when the script runs.
JavaScript
function domReady(fn) {
  if (document.readyState !== 'loading') {
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn, { once: true });
  }
}

// Usage
domReady(() => {
  console.log('DOM is ready');
  document.querySelector('#app').textContent = 'Hello!';
});
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.