HTML5 History API - do not fire window.onpopstate event when loading the first page

With the HTML5 history API, I created something like below:

(function (d, w) { $(function () { $("#indicator").hide(); if (typeof history.pushState !== 'undefined') { $("#citylinks a").click(function (e) { history.pushState({ path: this.href }, '', this.href); act(this.href); e.preventDefault(); }); w.onpopstate = function (event) { act(d.location); }; } function act(location) { $("#results").hide(); $("#indicator").show(); $.getJSON(location, function (data) { $("#results").html(data.result); $("#results").fadeIn(); $("#indicator").hide(); }); } }); })(document, window); 

The full code is here:

https://github.com/tugberkugurlu/MvcMiracleWorker/commit/7c511f20678bbfe15462909c794eb323ce615372#diff-3

The problem I have here is that I do not want to fire the w.onpopstate event on the first page of the page from the server.

The reason I would like to do this is because I would like to populate a server-side page, and I don't want client-side code to do this. If I remove the w.onpopstate event, I cannot catch the history.go() events.

Is there any way to solve this problem?

+4
source share
1 answer

A very simple approach:

 w.onpopstate = function () { w.onpopstate = function (event) { act(d.location); } } 

This means that the first time the onpopstate event is onpopstate your function is installed on the event handler (replaces the current handler), effectively creating noop when the event is executed when the page loads.

+4
source

Source: https://habr.com/ru/post/1392439/


All Articles