I'm playing with window.onpopstate
, and there is a thing that annoys me a little bit:
Browsers tend to handle the popstate event differently on page load. Chrome and Safari always emit a popstate event on page load, but Firefox doesn't.
I tested it, and yeah, in Chrome and Safari 5.1+ the popstate event is fired on page load, but not in Firefox or IE10.
The problem is, that I want to listen only to popstate
events where user clicked the back or forward button (or the history was changed via javascript), but don't want to do anything on pageload.
By other words I want to differentiate the popstate
event from page load from the other popstate
events.
This is what I tried so far (I'm using jQuery):
$(function() {
console.log('document ready');
setTimeout(function() {
window.onpopstate = function(event) {
// Do something here
}, 10);
});
Basically I try to bind my listener
function to popstate
late enough to be not bound on page load, only later.
This seems to work, however, I don't like this solution. I mean, how can I be sure that the timeout chosen for setTimeout is big enough, but not too big (because I don't want it to wait too much).
I hope there is a smarter solution!
popstate
happens just after theonload
processing which means 1ms is always enough to postpone thepopstate
registration (because JS has no multi-threading and process the postponed functions in the order they were registered). – Radek Pech Feb 14 '17 at 10:05