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

177
Vistas
Document load event not being called after refresh

I have the following function:

jQuery(document).ready(function(){
    window.addEventListener("load", function (){
        alert("hello");
});

It works on the first run, but then stops working when I hit the refresh button.

If I empty the cache or hard reload, it works again once.

What is going on? How can I fix this?

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

0

Try adding the handler outside of jQuery's document.ready():

window.addEventListener("load", function (){
 ...
});

jQuery(document).ready(function(){
  ...
};

On the first run the page might take time to load external resources (such as images). During that time jQuery(document).ready(...) is called.

When it finishes loading the external resources, the load event is fired and the function works correctly.

Weirdly enough, upon refresh, the resources are already cached, so the window.load event is fired so fast and occurs before jQuery(document).ready(), and since you add the event handler after the event was fired, the handler is not called. When you cleared the cache it worked again.


Alternatively, you can check the document for completion first like so:

function document_loaded(){
    // To be called when the document is loaded.
    ...
};

document.readyState == "complete" ? document_loaded() : window.addEventListener("load", document_loaded);

This will work no matter where you place the code.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you want to run a script each time the page is loaded the best way is to put the code directly into the main function:

jQuery(document).ready(function(){
    alert("hello");
};

From the documentation : https://learn.jquery.com/using-jquery-core/document-ready/ :

Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

If you want to wait also that your assets are loaded you should write:

jQuery(window).on("load", function(){
    alert("hello");
});
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