Ad

Hooking Javascript Onload For A Specific JS File

After a lot of troubleshooting, I found that my ga() commands were failing as they were running before Google Analytics was loaded in my Shopify store. I found a sample code snippet that supposedly delays the commands until GA has loaded, but it is using JQuery which my site doesn't use.

<script>
  $(window).ready(function() {
    $('head script[async][src*="analytics"]').on('load', function() {
      ga('set', 'dimension1', 'insert_value');
      ga('set', 'dimension2', 'insert_value');
      ga('set', 'dimension3', 'insert_value');
    });
  });
</script>

I'm looking at how to convert this to pure Javascript, and I am thinking I can possibly use addEventListener() to wait until it loads instead but not positive. What functions should be used to hook in to the loading of another Javascript file?

Ad

Answer

You are on the right track, I guess it look like your event is not fired because you have some issues with the loading order (i.e. the event being fired before you register the handler). The following should cover that case. The only requirement is that the script tag itself is inserted before DOMContentLoaded is fired.

document.addEventListener("DOMContentLoaded", function() {
  const loaded = function() {
    console.log("Script loaded");
  }
  if (ga !== undefined) {
   loaded()
  } else {
   document.querySelector('script[async][src*="analytics"]').addEventListener("load", loaded);
  }
});
<script src="https://www.google-analytics.com/analytics.js" async="true"></script>

Ad
source: stackoverflow.com
Ad