Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One strange issue about $.load()

This is the file I'm using $.load() to load into DOM:

<script type="text/javascript">
    $('.close').click(function() { alert(1) });
</script>
<div class="close">
    click me
</div>

Say,it seems to me that the <script> part will automatically be delayed when it's loaded ,is that a feature of $.load()?

If so,how is that implemented?

Feels amazing!

like image 208
omg Avatar asked Jan 24 '23 05:01

omg


1 Answers

I've read through the jQuery source, and here's what I've found:

(line numbers reference the uncompressed jQuery 1.3.2)

  1. jQuery.load ultimately gets the response and calls the jQuery html method with the result to insert it. (around line 3267)
  2. jQuery.html then calls the jQuery append method. (line 488)
  3. jQuery.append then calls the domManip method with a callback function that inserts the DOM nodes. (line 253)
  4. domManip (at line 514) is a little tricky, but ultimately it does in fact pass the DOM nodes to the callback to be inserted, then calls evalScript for each script after inserting the DOM nodes, regardless of their order in the html that was loaded. (line 526).

Hence, jQuery does in fact execute the scripts in a delayed fashion!

use the source, Luke.

like image 160
Gabriel Hurley Avatar answered Jan 31 '23 21:01

Gabriel Hurley