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

Asked

Viewed 1,361 times

0

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

I’m developing the screens first, then connect with the comic and make 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 function load() 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 well, however, by clicking on the links 8-10 times or more, the requested screen takes time to appear (it is as if the browser was crashing), in addition, the browser even consumes up to 70% of the CPU when I request a page (remembering that all this only occurs after browsing several times between the pages, when I give a refresh on the page everything goes back to normal).

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

  • You’re probably carrying one javascript which adds the function to the menu items. As more clicks you make, but functions you will add to the items and more requests these items will make. The ideal is to use a simple request (can be $.GET) and only load what you need. (No JS already added).

  • Try to use html() in place of load()

  • @Valdeirpsr, that’s exactly what’s going on! I put an Alert in the $.ajax Success and saw that every time I click on a link the request is made again and increases...

  • @Valdeirpsr Could you give me an example of how to do with $.get? Another question, I am inserting my script file together with the pages because I tried to do before without inserting and it did not work the functions I have on the requested pages. Making with $.get even without inserting them again functions will work?

2 answers

0

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

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

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

  • Ricardo, thank you for the reply. I did exactly as you mentioned, but continued in the same way :(

0


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

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

To fix this, you need to Filter what you will add, 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>
            /* 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) )
                });
            })

            /**
             * 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>
  • Oops, thank you so much! It all worked perfectly, now without choking. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.