jquery ready function: script not detecting a function
There is a web page with place holder (a normal div). Via ajax calls I am loading a <form>
and a <script>
into the place holder. The script contains necessary javascript to initialize the form (i.e. for e.g. disable the controls so as to make form read-only, etc). Here is a piece of code I have; it works, but the commented part doesn't work. Because the script engine cannot find the object tristate_DisableControl which is a function in one of those scripts I call via ajax.
$(doc开发者_StackOverflowument).ready(function() {
// $('#site_preferences_content div').each(function() {
// if (typeof (window.tristate_DisableControl) == 'undefined') {
// if (typeof (window.console) != 'undefnied')
// console.log((new Date()).toTimeString() + ' not logable');
// pausecomp(1000);
// }
// else
// tristate_DisableControl(this);
// }); //end $('#site_prefrences_content div').each()
setTimeout(function() {
$('#site_preferences_content div').each(function() { tristate_DisableControl(this); })
}, 1000);
});
I thought by the time $(document).ready() executes the DOM will be properly loaded...
The ready
event happens when the page is finished loading. It doesn't wait for asynchronous AJAX calls to complete.
To run the code once the extra content is loaded, you use the callback of the load
method. Example:
$('#site_preferences_content').load('content.html', function() {
$('#site_preferences_content div').each(function() {
tristate_DisableControl(this);
}
});
I'm not sure I've understood your question correctly, but if the declaration of tristate_DisableControl
is returned by an AJAX call, then no, DOMReady
does not wait until all AJAX calls are executed (after all, how could it possibly know how many AJAX calls will be made?)
You have to use the success
/ complete
callback of the AJAX function to find out when it has finished loading.
Document ready event fires when whole document is loaded, which excludes scripts loaded using ajax, because if that wasn't the case, ready event would probably never fire if your script keeps making ajax calls.
You should use callbacks on ajax loading methods for this.
精彩评论