Skip to content
Advertisement

Defer JavaScript execution till the content has been added to Document

I am trying to load some content into a page using Ajax. The html that is loaded contains some JavaScript code. Even though the code is wrapped within $(document).ready, it gets executed before the content is inserted into the document, because the parent document’s Dom is ready by the time the content is loaded.

How can I defer the execution of the code, until the content has been inserted into the document. Here is the html that I am trying to load (this is the code for openid-selector)

<script type="text/javascript" src="/js/openid-jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    alert('ajax-html');
    openid.init('openid_identifier');
});
</script>
<!-- Simple OpenID Selector -->
<form action="try_auth.php" method="get" id="openid_form">
    <input type="hidden" name="action" value="verify" />

    <fieldset>
            <legend>Sign-in or Create New Account</legend>

            <div id="openid_choice">
                <p>Please click your account provider:</p>
                <div id="openid_btns"></div>
            </div>

            <div id="openid_input_area">
                <input id="openid_identifier" name="openid_identifier" type="text" value="http://www.joycebabu.com" />
                <input id="openid_submit" type="submit" value="Sign-In"/>
            </div>
    </fieldset>
</form>

Update : Removed the noscript tag

Advertisement

Answer

It seems that the problem is that openid.init() is loading its own data and you want to manipulate that data after it has been loaded synchronously. There are a couple solutions:

Associate a callback function that executes when the asynchronous load is complete. Does the openid lib not offer you this functionality?

If you know the valid selectors of the data elements you want to manipulate before they’ve been added to the DOM, you can use .live().

I notice you are using the noscript tag. I advise against this strongly. Do all of your DOM manipulation through JS.

Advertisement