$(document).ready(handler) executes once the DOM is fully loaded. If content is later added to the page using AJAX, which contains a $(document).ready(handler) function, this function is executed immediately, per the jQuery API. Additionally, .ready can only be called on a jQuery object matching the current document.
This is not what I want, however 🙂
How can I achieve this .ready type of functionality for data loaded via AJAX after .ready has already fired, in a cross-browser compliant manner?
EDIT:
Here’s a very simplified example. I do have a problem I’m trying to solve, but I’m more interested in understanding the way to do this properly.
Basically, the .ready function in ajaxPage.html is firing before importantDependency.js is completely loaded, so the first load of ajaxPage, importantDependency is missing, but subsequent loads see it.
index.html
...
<script type="text/javascript">
$(document).ready(function() {
alert("The document is ready");
$('#myButton').click(function() {
$('<div></div>').dialog({
open: function () {
$(this).load('ajaxPage.html');
}
});
});
});
</script>
...
ajaxPage.html
...
<script type="text/javascript" src="importantDependency.js"></script>
<script type="text/javascript">
$(document).ready() {
$('#thing').leverageImportantDependency();
});
</script>
...
EDIT 2:
I want to do this FROM the loaded content, not from the page calling the content. Modifying the calling page means duplicating code in every instance where this is called. I’d like the behavior to be attached to the content, not the page calling it.
Generally, you will want to do something like this:
That is to say, fire off something once the content has been replaced, by utilizing the appropriate ajax callback. Other examples include:
See:
EDIT: From what I understand from your edit, you want attach something, such as a an event handler or a plugin to some elements that keep getting replaced. There are a few ways to do this:
demonstrated above.
.liveor.delegate..liveQuery.