Insert content from an HTML file into a DIV - jQuery / Ajax

0

I'm doing a GED system here for the company where I work (very simple, just to organize better).

I'm developing the screens first, then connecting to the DB and making things work.

I have a menu that is left with the links to navigate between the pages. On the right I insert the contents of the pages into a DIV called #conteudo , for this I am using the load() function of jQuery. As below:

// Carrega o conteúdo das páginas dentro da div#conteudo    
$('.carrega_pagina').click( function(){ 

    var href = $(this).attr('href'); // pega o valor do atributo href da âncora clicada
    $('#conteudo').load(href);
    return false;
});

This has worked fine, however, when clicking on the links about 8-10 times or more, the requested screen takes time to appear (it is as if the browser has been crashing), in addition, the browser consumes up to 70% of the CPU when I request a page (remembering that this only occurs after browsing several times between the pages, when I give a refresh on the page everything returns to normal).

I wanted to know if there is a better way to embed the contents of the other pages in this DIV.

    
asked by anonymous 07.03.2018 / 15:03

2 answers

0

This happens because during .load( URL ) you are bringing some JavaScript repeated codes. This causes the menu elements to add more and more click events.

These events are added so many times that instead of making a request, you can make 100 requests at once. Of course it will depend on how many times you click.

To fix this, you need to filter what you're adding, for example:

page1.html

<!DOCTYPE hml>
<html>
    <head>
        <title>Title of the document</title>
    </head>

    <body>
        <ul id="menu">
            <li><a href="page1.html">Page 1</a></li>
            <li><a href="page2.html">Page 2</a></li>
            <li><a href="page3.html">Page 3</a></li>
            <li><a href="page4.html">Page 4</a></li>
        </ul>

        <div id="content">
            <p>The content of the document...</p>
        </div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script>/*Carregaapágina*/$("#menu li a").click(function(e) {
                e.preventDefault();

                $.get( $(this).attr("href") , function(result){
                    let d = document.createElement("div");
                    d.innerHTML = result;

                    /* Adiciona o conteúdo da div#content da página dois na div#content da página atual */
                    document.querySelector("#content").replaceWith( d.querySelector("div#content") );

                    /* Executa todos os javascript que está dentro da div#content */
                    document.querySelectorAll("#content script").forEach( script => eval(script.innerHTML) )
                });
            })

            /**
             * Utilize o .on para elementos dinâmicos
             * Dessa forma, o jQuery irá verificar todos
             * os eventos "click" e depois irá verificar
             * se o evento percente ao elemento #btnTest
             * caso pertença, executa a função
             */
            $("body").on("click", "#btnTest", function() {
                alert( $(this).attr("data-msg") )
            })
        </script>
    </body>
</html>

page2.html

<!DOCTYPE hml>
<html>
    <head>
        <title>Title of the document</title>
    </head>

    <body>
        <ul id="menu">
            <li><a href="page1.html">Page 1</a></li>
            <li><a href="page2.html">Page 2</a></li>
            <li><a href="page3.html">Page 3</a></li>
            <li><a href="page4.html">Page 4</a></li>
        </ul>

        <div id="content">
            <p>Tudo certo</p>
            <button type="button" id="btnTest" data-msg="O JavaScript está funcionando.">Alerta</button>

            <script>alert("JavaScript liberado")</script>
        </div>

        <script>
            /* Carrega a página */
            $("#menu li a").click(function(e) {
                e.preventDefault();

                $.get( $(this).attr("href") , function(result){
                    let d = document.createElement("div");
                    d.innerHTML = result;

                    /* Adiciona o conteúdo da div#content da página dois na div#content da página atual */
                    document.querySelector("#content").replaceWith( d.querySelector("div#content") );

                    /* Executa todos os javascript que está dentro da div#content */
                    document.querySelectorAll("#content script").forEach( script => eval(script.innerHTML) )
                });
            })

            alert("JavaScript repetido")
        </script>
    </body>
</html>
    
07.03.2018 / 15:56
0

An alternative is to use Ajax itself to do this. The secret is to set dataType to "html", like this:

$('.carrega_pagina').click(function () {
    var href = $(this).attr('href'); 
    $.ajax({
        url: href,
        dataType: 'html',
        success: function (html) {
            $('#conteudo').html(html);
        }
    });
    return false;
});

Now do the tests with multiple clicks and see if it caters better than .load()

    
07.03.2018 / 15:09