AJAX history button support without crazy

I used the jQuery address several times to support the back button in small asynchronous applications.

When all AJAX requests do the same thing (that is, requesting the page asynchronously and replacing the HTML element with the request), the implementation can be easy.

When AJAX requests can do different things, say, open an overlay in one case and change the whole page content in another case, everything becomes messy.

As a result, I got some really crappy code for me having to go through a lot of if statements to parse the hash value (# / somepage / someotherpage).

I always repeated to myself: there must be a better way to do this.

Has anyone gone through the same problem and can offer a solution?

If not, check out my idea and tell me what you think.

My idea is to create an object that emulates an object window.history, but only for AJAX history, let it call it "ajaxhistory". Each time a page is requested asynchronously, the following happens:

ajaxhistory[i] = {
    url: 'here the url',
    type: 'overlay'
    otherusefulinfo: 'whatever'
}
i++

So for example:

if(moving back or forward){
    if(currenturl == ajaxhistory[i-1].url){
        // i'm going back
        // i'm able to know what type of action i should take thanks to
        // ajaxhistory[i-1].type and ajaxhistory[i-1].otherusefulinfo
    }
 }

I like this idea because it will make my code a lot easier to read, mantain and change. Suppose I want to add new functionality ... I can add a new type, and I work with it, while usually I need to edit a lot of crappy if statements.

What do you think? Were there any problems in terms of performance?

+3
source share
2 answers
+1

html5:
window.history.pushState({type: 'overlay'}, title, url), - JS.

:


window.onpopstate = function(event) {
  alert( event.state.overlay);
}

https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

0

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


All Articles