Pause jQuery ready events until multiple HTML DOM updates are finished
I am using jQuery to make AJAX submits and receive JSON replies containing multiple DOM IDs and corresponding HTML fragments that I need to update. Thus, I do multiple jQuery.html
calls like $('#id1').html('...'); $('#id2').h开发者_如何转开发tml('...');
.
For every fragment containing a ready
handler like $(function(){...});
, the event is immediately triggered. I'd prefer to call it once after all updates were made.
Is there any way to do that?
From what I've read so far, a jQuery.trigger() could be used to manually trigger the ready
event. But I'd need to save and restore the current handlers or postpone event delivery by overwriting the jQuery internals somehow. The latter is something that I'd like to avoid, maybe there's some best practice I don't know yet?
Have a look at the holdReady
function.
See: http://api.jquery.com/jQuery.holdReady/
I would start by moving the js you have in your views into external js files where they can be invoked from the ajax callback functions.
As you are finding out in-page ready events can soon leave you feeling out of control and become very hard to maintain. Regain control, namespace your js up into logical sections and lose the ready reliance.
There is no need for ready statements if you include your js before the closing body tag. The best advice I can give is to start being explicit in your apps lifecycle about what js gets called when, rather than relying on the well over abused ready statement.
Rebecca Murphy has written some very good articles/presentations about this.
精彩评论