Last active
August 30, 2019 19:03
-
-
Save ryan-roemer/5d177346a4cb96f774b82243cf7f301f to your computer and use it in GitHub Desktop.
Analytics vanilla HTML example using ESM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Using Analytics in HTML</title> | |
</head> | |
<body> | |
<button id="track"> | |
Track Click | |
</button> | |
<button id="page-view"> | |
Fire page view | |
</button> | |
<button id="identify-visitor"> | |
Identify visitor | |
</button> | |
<script> | |
// Polyfill process. | |
// **Note**: Because `import`s are hoisted, we need a separate, prior <script> block. | |
window.process = window.process || { env: { NODE_ENV: "production" } }; | |
</script> | |
<script type="module"> | |
/* Include `analytics` from CDN */ | |
import { init } from 'https://unpkg.com/analytics/lib/analytics.browser.es.js?module'; | |
import analyticsGA from 'https://unpkg.com/analytics-plugin-ga/lib/analytics-plugin-ga.browser.es.js?module'; | |
/* Initialize analytics */ | |
const Analytics = init({ | |
app: 'analytics-html-demo', | |
debug: true, | |
plugins: [ | |
// attach google analytics plugin | |
analyticsGA({ | |
trackingId: 'UA-126647663-3' | |
}) | |
// ... add any other third party analytics plugins | |
] | |
}) | |
/* Fire page view */ | |
Analytics.page() | |
/* Attaching a listener */ | |
Analytics.on('*', ({ payload }) => { | |
console.log(`Event ${payload.type}`, payload) | |
}) | |
/* Bind listeners */ | |
document.querySelector('#track').addEventListener('click', () => { | |
Analytics.track('buttonClicked'); | |
}); | |
document.querySelector('#page-view').addEventListener('click', () => { | |
Analytics.page(); | |
}); | |
document.querySelector('#identify-visitor').addEventListener('click', () => { | |
Analytics.identify('user-123', { | |
pro: true, | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment