Jquery - loading embedded javascript via AJAX

I put together a quick prototype to try to establish some very simple truths about what inline JavaScript can do when it loads using AJAX:

index.html

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    </head>
    <body>
            <script type="text/javascript">
                    $('p').css('color','white');
                    alert($('p').css('color'));
                    // DISPLAYS FIRST but is "undefined"

                    $(document).ready(function(){
                        $('#ajax-loaded-content-wrapper').load('loaded-by-ajax.html', function(){
                            $('p').css('color','grey');
                            alert($('p').css('color'));
                            // DISPLAYS LAST (as expected)
                        });
                        $('p').css('color','purple');
                        alert($('p').css('color'));
                        // DISPLAYS SECOND
                    });
            </script>
            <p>Content not loaded by ajax</p>
            <div id="ajax-loaded-content-wrapper">
            </div>
    </body>
</html>

uploaded to ajax.html

<p>Some content loaded by ajax</p>

<script type="text/javascript">

    $('p').css('color','yellow');
    alert($('p').css('color'));
    // DISPLAYS THIRD

    $(document).ready(function(){
        $('p').css('color','pink');
        alert($('p').css('color'));
        // DISPLAYS FOURTH
    });

</script>

<p>Some content loaded by ajax</p>

<script type="text/javascript">

    $(document).ready(function(){
        $('p').css('color','blue');
        alert($('p').css('color'));
        // DISPLAYS FIFTH
    });

    $('p').css('color','green');
    alert($('p').css('color'));
    // DISPLAYS SIX

</script>

<p>Some content loaded by ajax</p>

Notes:

a) All of the above (except the first) successfully changes the color of all paragraphs (in Firefox 3.6.3).
b) I used alertinstead console.log, because the console undefinedwhen called in the "loaded" HTML.

Truths (?):

  • $(document).ready() does not treat the "loaded" HTML as a new document or rereads the entire DOM tree, including loaded HTML, it is meaningless inside the loaded AJAX content.
  • JavaScript, "" HTML, DOM.
  • jQuery "" HTML DOM.
  • firebug '' HTML, DOM ( a)

"" ( )?
, ?

+3
1

: .load() .

№1, , , . , . , DOM, . " DOM", .

# 2: JavaScript, , - - , . , ; DOM, .

# 3. jQuery , script , . .

# 4. Firebug - , , , . DOM Firebug, () , .

+2

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


All Articles