I've noticed a lot of third party monitoring tools that you need to copy and paste into your website follows this pattern:

<!-- For example, Loggly -->
  <script type="text/javascript" src="//cloudfront.loggly.com/js/loggly.tracker-latest.min.js" async></script>
  <script>
      var _LTracker = _LTracker || [];
      _LTracker.push({'logglyKey': 'blah-blah-blah',
      'sendConsoleErrors' : true,
      'tag' : 'loggly-jslogger'  });
  </script>

For efficiency's sake, the loggly.tracker-latest.min.js is being loaded async, which is great.

My understanding of this line: var _LTracker = _LTracker || []; is that it's saying in case when it's called _LTracker hasn't loaded yet from the loggly.tracker-latest.min.js, then initialize a blank array [] to push the data.

In the situation above where the data containing logglyKey is in a newly init Array, then the only way to actually capture that info is if the external script loggly.tracker-latest.min.js, once it finishes loading, has some code (not visible here) that then redefines _LTracker and pulls in any information previously initialized in an empty Array. Right? Like, there's no way the code as it is visibly written moves the logglyKey info from the blank Array to the actual _LTracker...

Because so, I reasoned that I could also choose to modify the code myself below

  <script type="text/javascript" src="//cloudfront.loggly.com/js/loggly.tracker-latest.min.js" async></script>
  <script>
      $(window).on("load",function() {
        var _LTracker = _LTracker;
        _LTracker.push({'logglyKey': 'blah-blah-blah',
        'sendConsoleErrors' : true,
        'tag' : 'loggly-jslogger'  });
      })
  </script>

However the code above actually fails with Uncaught TypeError: Cannot read properties of undefined (reading 'push'), because _LTracker wasn't yet defined. But I'm not sure why because window.on("load") should have waited for the external script to load?

0

There are 0 best solutions below