Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
How to prevent loading multiple views when navigating fast with the back and forward button

I am working on a web application where the user can navigate between different pages (or 'partial views') which are loaded in with AJAX. I made it so when the user presses the back and forward button in the browser that the application returns the correct view depending on the url the adress bar contains on that moment.

My problem: When I navigate slowly by pressing the back and forward button in the browser it works like normal. But when I repeatedly press the back or forward button it loads multiple views within the application.

My question: Is there a way to prevent multiple views from loading in the application and only load the view which is supposed to load?

My Code:

$(window).on("popstate", function (e) {
    $(".UserNavigation li").removeClass("active");
        LoadContent.init();
    })

    var LoadContent = {
    init: function (url, query) {

        var Content = { }
        var PathName;

        if (url == null) {
            PathName = window.location.pathname;
            Content.url = "ContentArea/" + PathName;
        }    
        else {
            var Controller = "ContentArea/"
            Content.url = Controller + url
        }            

        if (query)
            Content.query = query       

        LoadContent.Loading(this);

        xhr = $.ajax({
            type: "POST",
            url: Content.url,
            data: { query: Content.query, type: 0 },
            success: function (data) {  

                LoadContent.ApplyContent(data);

            },
            error: function () {

            },
            complete: function (data) {
                if (url != null)
                    LoadContent.UpdateHistory(data, url);
            }
        })
    },

    ApplyContent: function (data) {
        $("#ContentLoading").animate({
            opacity: 0
        }, 200, function () {
            $("#ContentLoading").addClass("hidden");
            $("#ContentArea").append(data).addClass("visible");
            LoadContent.UpdateMenu();
        })

        return this;
    },

    Loading: function () {
        $("#ContentArea").children().remove();
        $("#ContentLoading").removeClass("hidden");
        $("#ContentArea").removeClass("visible");
        $("#ContentLoading").animate({
            opacity: 1
        }, 200)
    },

    UpdateHistory: function (data, url) {
        var DataToSave = {
            StateURL: url,
        }

        history.pushState(DataToSave.StateURL, url, url)
    },

    UpdateMenu: function () {
        var CurrentPath = window.location.pathname;
        $(".UserNavigation li").removeClass("active");
        $("[href='" + CurrentPath + "']").parent().addClass("active");
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In the following part

ApplyContent: function (data) {
    $("#ContentLoading").animate({
        opacity: 0
    }, 200, function () {
        $("#ContentLoading").addClass("hidden");
        $("#ContentArea").append(data).addClass("visible");
        LoadContent.UpdateMenu();
    })

    return this;
},

Change .append() into .html(). This will prevent the extra content from filling up more space, but completely replace the html of #ContentArea.

Like Parth said, you should also abort the running Ajax requests and start a new one. This won't prevent the server from sending you your results, so it's best to also cancel all old requests on the server when you're sending new ones.

over 4 years ago · Santiago Trujillo Relatório

0

In your case ajax response load data so what happen if you send multiple request,off course ajax data(view) replace old one.so you need to stop previous ajax request

 if (typeof this.xhr !== 'undefined')
       this.xhr.abort();

aboove code stop previous ajax request

 this.xhr = $.ajax({
    type: "POST",
    url: Content.url,
    data: { query: Content.query, type: 0 },
    success: function (data) {  

        LoadContent.ApplyContent(data);

    },
    error: function () {

    },
    complete: function (data) {
        if (url != null)
            LoadContent.UpdateHistory(data, url);
    }
})
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda