简体   繁体   中英

HTML5 History API - Do not fire window.onpopstate event at the first page load

With 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 complete 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 at the first time page comes from the server.

The reason I would like to do this is that I would like to fill the page at the server side and I do not want client side code to do that. If I remove w.onpopstate event, I won't be able to catch history.go() events.

Is there any way to solve this problem?

A very simple approach would be this:

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

This means that the first time the onpopstate event fires, your function is set to the event handler (replacing the current handler), effectively creating a noop for when the event runs on page load.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM