Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda