title: How to wait for page to finish loading all content before running script or how to best detect major DOM changes
body: <p>I'm making a text replacing extension (of sorts) using the method described <a href="http://9to5google.com/2015/06/14/how-to-make-a-chrome-extensions/" rel="nofollow">here</a> as a basis for replacing text.</p>
  
  <p>Here is the important piece of code </p>
  
  <pre><code>var elements = document.getElementsByTagName('*');
  
  for (var i = 0; i &lt; elements.length; i++) {
      var element = elements[i];
  
      for (var j = 0; j &lt; element.childNodes.length; j++) {
          var node = element.childNodes[j];
  
          if (node.nodeType === 3) {
              var text = node.nodeValue;
              var replacedText = text.replace(/[word or phrase to replace here]/gi, '[new word or phrase]');
  
              if (replacedText !== text) {
                  element.replaceChild(document.createTextNode(replacedText), node);
              }
          }
      }
  }
  </code></pre>
  
  <p>Now this works fine in 99% of cases, but on some computers (I'm assuming based on the speed of the computer and what it has cached) this code will not work on certain websites, most importantly on google searches. The script definitely runs, but it doesn't find anything to replace. My best guess is that it is loading and running the script before it finishes loading and adding all the data from google onto the DOM.</p>
  
  <p>I have two questions</p>
  
  <p>1) Is there any way to detect that google has finished doing what it needs to do before running the script? Or is this inherently impossible because (I assume) there is some asynchronous stuff happening. </p>
  
  <p>2) If I can't detect that its fully finished loading, what is the best way to detect that a text or image element has been added to the DOM (or edited on the DOM) so that I can rerun the function that replaces the text?</p>
  
  <p>Thanks in advance for the help.</p>