Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
Window.onload blocking DOM render, setTimeout doesn't

I have tested this in chrome and safari, both having same result.

When i try to run a loop after window onload event, it keeps waiting for the loop to end before rendering the regular DOM above it.

However, if i call the loop code through a setTimeout, even if it's of 0 millisecond, it loads the DOM and then runs the loop.

Shouldn't window onload event do this by default? I want to understand how can we truly make the javascript code run after the DOM is rendered.

Thanks.

<!DOCTYPE html>
<html lang="en">
<body>
    <div id="root">
        foo
    </div>

    <script>

        window.onload = ( () => {
            // b()
            setTimeout(() => {
                b()
            }, 0);
        });

        function b() {

            let i = 0
            while (i < 400000000) {
                i++
            }
            document.getElementById('root').innerHTML = i

        }

    </script>
</body>

</html>

However if we comment out the b() inside setTimeout and uncomment the b() above it, it will wait till b() finishes before rendering the DOM.

Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The onload event fires when all the resources have been loaded. Here there is no external resource to load, so it will fire instantly, before the next painting frame.

The timeout may let the browser update the rendering, but it's not a given, the next painting could happen after the timeout.

If you want to ensure the page has been painted at least once before executing your script, then wait for the next painting frame, by calling requestAnimationFrame() and in the callback wait just the next task (e.g with setTimeout(fn, 0)):

requestAnimationFrame(() => setTimeout(yourScript, 0));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda