Skip to content

Instantly share code, notes, and snippets.

@pimterry
Last active May 18, 2016 13:17
Show Gist options
  • Save pimterry/63d9160c6eb67fe8f6a389854bf9364b to your computer and use it in GitHub Desktop.
Save pimterry/63d9160c6eb67fe8f6a389854bf9364b to your computer and use it in GitHub Desktop.
var components = require("server-components");
var GoogleAnalytics = components.newElement();
/**
* A <google-analytics tracking-id="UA-7123123-1"> element, which adds the
* standard Google Analytics scripts to your page, for given the tracking id.
*/
GoogleAnalytics.createdCallback = function (document) {
// Use the normal DOM API methods
var trackingId = this.getAttribute("tracking-id");
var scriptTag = document.createElement("script");
// ES6 without build steps! Server-side, you choose the runtime.
scriptTag.innerHTML = `
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '${trackingId}', 'auto');
ga('send', 'pageview');
`;
this.appendChild(scriptTag);
};
components.registerElement("google-analytics", { prototype: GoogleAnalytics });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment