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?
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.
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");
});