Listening for Loaded Async Script

This demonstrates a few ways that a blocking non-async script can listen for an async script to load:

  1. Using the an event system provided by the async library itself, e.g. (window.myLib = window.myLib || []).push(callback).
  2. An onload event handler attribute on the script[async]. Not ideal since it requires 'unsafe-hashes' for CSP.
  3. Adding a load event listener to the script[async] which has a defined id. Ideal, as long as we can be sure that the script[async] will not finish loading before the subsequent inline blocking script with script.addEventListener('load', ...) can run. This is not reliable since the async script could load before the inline script is executed. See demonstration.
  4. Listening for the readystatechange event until document.readyState === 'complete'. The downside here is it waits for all async scripts and other assets to have downloaded (so similar to the load event on window).
  5. The load event on the window. (Worse than readystatechange.)
  6. Polling with setInterval. (The worst).
  7. Using MutationObserver to listen for subsquent parsing of the script[async] and adding the load event via addEventListener. This also works for blocking scripts! (Props to Noam Rosenthal for this approach.)
  8. Adding a load event listener on the document.documentElement with the capture option (aka useCapture) set to true. The best?

Did I miss anything?




    
    
    

    
@westonruter