window bind POPSTATE

前端 未结 8 1982
一整个雨季
一整个雨季 2020-12-07 21:25

Given the following:

$(window).bind(\"popstate\", function() {
    alert(\'popstate\');
});

On first load, the alert fires with FireFox and

8条回答
  •  抹茶落季
    2020-12-07 22:10

    I convert @Nobu & @Tamlyn answers into an object, I also add a little fix by adding "window.history.state !== null". In some browsers the history.state exists, but it's null so the it was not working.

    /**
     * The HTML5 spec was changed in 2011 to state popstate should not 
     * fired on page load. Chrome(34) & Firefox(4) has fixed the bug but 
     * some browsers (e.g. Safari 5.1.7) are still fire the popstate on
     * the page load. This object created from the Pjax Library to handle 
     * this issue.
     */
    var popstatePageloadFix = {
    	popped : ('state' in window.history && window.history.state !== null),
    	initialUrl : location.href,
    	initialPop : false,
    	init : function() {
    		this.initialPop = !this.popped && location.href == this.initialUrl;
    		this.popped = true;
    		return this.initialPop;
    	}
    };
    
    $(window).on("popstate", function (event) {
    	
    	// Ignore initial popstate that some browsers fire on page load
    	if ( popstatePageloadFix.init() ) return;
    	
    	...
    
    });

    Thanks @Nobu! Thanks @Tamlyn!

提交回复
热议问题