When updating the pages of the application (say, I return to the previous page and repeatedly go to the next) all data on the page (title and name in the navbar, list of properties on the page, etc.) is doubled, once again it is triple, etc. . The content of the pages is dynamically created by me - I take the necessary data from the server using js and fill the page. In no way can I write a condition so that when dynamically creating elements on the page they are checked for the existence of duplicates.

    2 answers 2

    The solution to your problem is quite simple.

    Where the data needs to be filled in individually and the block is guaranteed to exist, update the entire block, if of course it changes over time. If the data is unchanged on the page, then ignore the update if there is data in the block.

    //Если данных в блоке нет if ($('#user_block').html().length==0) { //Вставить данные } 

    Where it is necessary to add and modify existing data (for example, a news feed), use special attribute (s) that identify the record (block), for example, the last update time and id.

     //получить блок по атрибуту data-id var block = $("div[data-id='" + id +"']"); //Если блока не существует if (block.length==0) { //Вставить блок с данными } //Если атрибут не равен дате последнего обновления if (block.attr('data-update')!=lastUpdate) { //Обновить блок } 

    Naturally, if the block is guaranteed to exist, it suffices to use the condition associated with the last update date.

    The main concept of the solution is to simply check the conditions on certain elements when receiving data from the server. Although, it would also be correct to set some flag if the data is unchanged on the page, so as not to request it once more.

    • Thank you, I wrote my answer in parallel) I do not understand why this option did not work out earlier, but now I tried again and everything worked. PS I will also analyze your version for the future! - PrinceOFF
    • For some reason, the condition: (// If there is no data in the block if ($ ('# user_block'). Html (). Length == 0) {// Insert Data}) does not work ... - PrinceOFF
    • I apologize, it works - I found what was the error - for example, if there is at least one space between the div blocks in the html markup, it will not work. This is due to the "beautiful" formatting of the code with the separation of div tags on different lines ... - PrinceOFF

    For some reason it did not work out earlier, but now I wrote a simple condition and it went:

     var elem1 = document.getElementById('userNAME'); if (!elem1) { // Create username in the top navbar $(".userName").append($userName); } else { console.log("userName is exists"); };