umami icon indicating copy to clipboard operation
umami copied to clipboard

On website, `ReferenceError: umami is not defined`

Open chris-m92 opened this issue 2 years ago • 2 comments

Describe the Bug

On occasion, something causes Umami to fail to send an event. The script loads via a 304 Not Modified HTTP code and, assumingly gets loaded into the site, however an event tracked ends up resulting in an undefined reference error.

Relevant code:

Root

        <script 
          defer 
          src="https://umami.MYDOMAIN.com/script.js" 
          data-website-id="MY-WEBSITE-ID"
          data-domains='MY-ASSIGNED-SITE'
        ></script>

Route

        try {
          umami.track('loadQuery', { type: 'storage' })
        } catch (error) {
          console.debug('Umami error: ', error)
        }

Results in an error.

Database

MySQL

Relevant log output

Uncaught (in promise) ReferenceError: umami is not defined
    at k (_index-DxOjFC2I.js:55:69117)
    at _index-DxOjFC2I.js:55:68450
    at sl (index-B6Ifai2I.js:40:24177)
    at Gn (index-B6Ifai2I.js:40:42061)
    at Fi (index-B6Ifai2I.js:40:36399)
    at mn (index-B6Ifai2I.js:38:3258)
    at yd (index-B6Ifai2I.js:40:40969)
    at gn (index-B6Ifai2I.js:40:39976)
    at Ba (index-B6Ifai2I.js:40:35511)
    at E (index-B6Ifai2I.js:25:1562)

Which Umami version are you using? (if relevant)

Self-Hosted

Which browser are you using? (if relevant)

Chrome

How are you deploying your application? (if relevant)

AWS

chris-m92 avatar May 28 '24 15:05 chris-m92

Closing this issue

After further review, the issue is not with umami itself, however, by following the documentation and including the defer directive in the <script> tag, it caused the bug as my umami.track statements which were actually attempting to send events prior to the download of the script.js. Those umami.track events were in a React.useEffect block with an empty dependency array, therefore running on mount. Removing the defer directive fixed this issue - requiring the download of the script.js prior to rendering/running the rest of the React code.

chris-m92 avatar May 28 '24 18:05 chris-m92

Note a better solution:

<p>...content before scripts...</p>

<script>
  document.addEventListener('DOMContentLoaded', () => alert("DOM ready after defer!"));
</script>

<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>

<p>...content after scripts...</p>

myesn avatar Sep 13 '24 09:09 myesn