renderOnDomReady.tsx 679 B

123456789101112131415161718192021222324252627282930
  1. let hasEventListener = false;
  2. const queued: Function[] = [];
  3. function onDomContentLoaded() {
  4. if (!queued.length) {
  5. return;
  6. }
  7. while (queued.length) {
  8. queued.pop()?.();
  9. }
  10. // We can remove this listener immediately since `DOMContentLoaded` should only be fired once
  11. document.removeEventListener('DOMContentLoaded', onDomContentLoaded);
  12. hasEventListener = false;
  13. }
  14. export function renderOnDomReady(renderFn: () => void) {
  15. if (document.readyState !== 'loading') {
  16. renderFn();
  17. return;
  18. }
  19. queued.push(renderFn);
  20. if (!hasEventListener) {
  21. document.addEventListener('DOMContentLoaded', onDomContentLoaded);
  22. hasEventListener = true;
  23. }
  24. }