title: How to guarantee that deferred JS scripts have executed?
body: <p>On my website I use javascript modules, which according to MDN are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#other_differences_between_modules_and_standard_scripts" rel="nofollow noreferrer">deferred by default</a>. I have some additional javascript which can only safely execute once these modules have loaded and executed. MDN indicates <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer" rel="nofollow noreferrer">here</a> that deferred script execution is guaranteed to have occurred by the time the <code>DOMContentLoaded</code> event has fired. Further, it is suggested <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event#checking_whether_loading_is_already_complete" rel="nofollow noreferrer">here</a> that you can also account for the case where this event has already fired like so:</p>
  <pre><code>function doSomething() {
    console.info('DOM loaded');
  }
  
  if (document.readyState === 'loading') {  // Loading hasn't finished yet
    document.addEventListener('DOMContentLoaded', doSomething);
  } else {  // `DOMContentLoaded` has already fired
    doSomething();
  }
  </code></pre>
  <p>The block above seems to be what I'm looking for. But documentation elsewhere on MDN leaves me unsure as to whether this is really correct. For instance, why does the <code>readystate</code> check above look for <code>loading</code> rather than <code>loading</code> OR <code>interactive</code>? The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState" rel="nofollow noreferrer">documentation</a> on <code>readystate</code> says that <code>loading</code> is followed by <code>interactive</code>, and that in the <code>interactive</code> state &quot; sub-resources such as <strong>scripts</strong>, images, stylesheets and frames are <strong>still loading</strong>.&quot;</p>
  <p>So it seems to me that there is an inconsistency here. Either the suggested <code>readystate</code> check is not sufficient to guarantee that <code>DOMContentLoaded</code> has fired, or <code>DOMContentLoaded</code> is not sufficient to guarantee that deferred scripts have completed.</p>