3
document.getElementById('my_id').innerHTML = 'A message';
// Next should only be executed once DOM manipulation has completed
.. do some stuff

I've seen this jQuery/Javascript - How to wait for manipulated DOM to update before proceeding with function, which suggests using a setTimeOut.

document.getElementById('my_id').innerHTML = 'A message';
setTimeout(function(){
     .. do some stuff 
},10);

However, this is a race, which I don't like. I need to be sure and also don't want to waste time waiting. One of the comments stated that even 0ms works because it puts it in a queue and is guaranteed to only execute after the DOM manipulation has completed. Is that absolutely certain? If so, where is this state or tested?

(The manipulation can be more complicated than this example, of course. The inserted HTML may even contain its own javascript that executes. The inserted JS execution does not have to be completed, but the rendering must have been completed.)

Community
  • 1
  • 1
user984003
  • 28,050
  • 64
  • 189
  • 285

2 Answers2

1

You can use both the legacy Web events or the newer Mutation observer.

Each time you manipulate the DOM some events are triggered, not just the loading one.

In this example you are inserting HTML, so you need to listen to DOMNodeInserted event at least.

pietro909
  • 1,811
  • 1
  • 19
  • 26
1

You should trigger the other event from the event listeners on the other actions. Basically you can have something like this

$(".button").click(function(){
// perform your actuibs and do some interesting stuffs
$(".anotherButton").click()
})

$(".anotherButton").click(function(){
// the other actions that needs to be performed after the first button clicked
})
Abiodun
  • 467
  • 3
  • 15