views:

91

answers:

2

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!

A: 

"The script won't work as expected if you access the file directly with a browser(when clicking to it,no alert).But if you loaded it to another page with $.load(),it will work(alert when you click). – Shore"

When you load the file in browser as itself, the reason why there's no alert when you click it is because when the browser reads the line "$('.close')...", there's no DOM object of class "close" yet, because the comes after the script tag.

You can resolve this by:

$(document).ready(function(){$('.close').click(function() { alert(1) });});

As for the delay part, it is because that when you use $.load(), the function loads the file first, then put the source into the DOM object. After putting source into the DOM object, it will then parse the <script> tags in your file. That's why your click event is binded successfully to your DOM objects with class close

thephpdeveloper
After putting source into the DOM object, it will then parse the <script> tags in your file. Did you say it according to jQuery source code?
Shore
that's what the logic should be. getting file source via ajax, put into dom, then parse for script.
thephpdeveloper
+9  A: 

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.

Gabriel Hurley
Great!
Shore