Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!