JavaScript Wait Page to be Loaded


Recently I am writing Chrome extension. I need to create DOM nodes and append the nodes to the original contents of the wepage. But when I tried to append my created DOM nodes to the nodes in the original content, nothing happened! I cannot see any of my nodes appended.

I investigate the problem and found that the original page use a lot of JavaScript to render contents of the page, and the DOM nodes of original contents are not ready for appending my created nodes. I tried to do some Google searches [1], and some answers said we can listen to onload event of DOMContentLoaded event. But the answer does not work in my case.

I wrote post of DOM ready [2] long time ago, and the trick in the post is periodically check if the node to which my nodes are appended is available. If the node is not ready, sleep for a while and check again until the node is available. I applied this trick to my case, and it worked!

The following is key point of the trick:

// wait the node to be ready
// check interval: 500ms
var timerId = setInterval(function() {
  var n = document.querySelector("css-selector-of-node");
  if (n != null) {
    // now the node is available, do something here.
    // and also clear the timer.
    clearInterval(timerId);
  }
}, 500);

Hope this would be helpful for those who have the same problem as me.


References:

[1]
[2]DOM Ready without JavaScript Frameworks