title: Execute callback after asynchronous task in external script is completed?
body: <p>Is it possible to run javascript function after external asynchronous script was loaded?</p>
  
  <p>After example.js runs (async. it seems), this is the result:</p>
  
  <pre><code>&lt;div class="keepthisdiv"&gt;Keep this text&lt;/div&gt;
  &lt;div class="removethisdiv"&gt;Remove this text&lt;/div&gt;
  &lt;div class="keepthisdiv"&gt;Keep this text&lt;/div&gt;
  </code></pre>
  
  <p>Example.js has to be run between body tags, if it's in the head, there is no output.</p>
  
  <p>Here is my div container and js code (<a href="https://stackoverflow.com/questions/4323723/how-to-run-a-javascript-function-after-a-specific-js-has-loaded">credits</a>):</p>
  
  <pre><code>&lt;div id="jscontainer"&gt;&lt;/div&gt;
  
  &lt;script&gt;
  
  function loadBackupScript(callback){
      if (typeof callback !== 'function') {
         throw 'Not a valid callback';  
      }
      var script = document.createElement('script');
      script.onload = callback;  
      script.src = 'http://www.example.com/example.js';
      script.type = 'text/javascript';
      var container = document.getElementById("jscontainer");
      container.appendChild(script);
  }
  
  loadBackupScript(function() {
  
  $( ".removethisdiv" ).remove();
  
  });
  
  &lt;/script&gt;
  </code></pre>
  
  <p>However, it doesn't remove a div with <code>removethisdiv</code> class. <code>loadBackupScript</code> obviously runs before <code>example.js</code> is completely parsed.</p>
  
  <p>How can I run <code>loadBackupScript</code> function right after <code>removethisdiv</code> class is inserted into DOM? I know that it is possible to use a timer and then remove it after few seconds, but it is unreliable, because external script's parsing times vary. Also, there are many different scripts on the same page, so I'd like to avoid waiting for page to load completely and I need to specifically target this script (example.js).</p>