Prevent JQuery injected script running before injected html from same file in DOM after AJAX call

时间:2018-11-09 17:37:25

标签: jquery ajax jquery-ui jquery-ui-dialog

I seem to have encountered a race condition when running scripts injected into my webpage over ajax. For example I have a file that looks like this:

<div id='test_id'>I'm a div</div>
<script>$(function(){alert('Do something to #test_id')});</script>

I am loading that file using JQuery's post method and attaching it to a JQueryUI dialog. Like so:

var $dialog = $("<div id='div_dialog'></div>")
    .dialog({
        autoOpen: false,
        title: 'NA',
        modal: true,
        width: '50%',
        buttons: {some button object},
    });
$dialog.dialog('open');

$.post(
    [url to get page], 
    {}, 
    function(data) {
        $('#div_dialog').html('<div id="messages"></div>' + data);
    });

The problem is that when the alert pops up, the dialog is showing on the page as expected, but it has no html in it. Then when I click away the alert the html shows as expected.

What I expect to happen, is that the html is attached, and then the script is run. This is not the case. I've tried $(document).ready() and $(window).load() as well as $(document).ajaxComplete() and $(document).ajaxSuccess() without any luck. It DOES work if I put it in a setTimeout with some millisecond delay. But thats.... wrong.

I should also mention that what I am hoping for is a solution that does not require me to change the AJAX request as I wont always have access to that file - others will be importing my created files over ajax using the pattern I specified.

0 个答案:

没有答案