Last active
September 7, 2018 15:50
-
-
Save brainix/4394158 to your computer and use it in GitHub Desktop.
CoffeeScript for Google Analytics
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
class GoogleAnalytics | |
@init: (webPropertyId) -> | |
@_initQueue webPropertyId | |
scriptTag = @_createScriptTag() | |
@_injectScriptTag scriptTag | |
true | |
@_initQueue: (webPropertyId) -> | |
window._gaq ?= [] | |
window._gaq.push ['_setAccount', webPropertyId] | |
window._gaq.push ['_trackPageview'] | |
@_createScriptTag: -> | |
scriptTag = document.createElement 'script' | |
scriptTag.type = 'text/javascript' | |
scriptTag.async = true | |
protocol = location.protocol | |
scriptTag.src = "#{ protocol }//stats.g.doubleclick.net/dc.js" | |
scriptTag | |
@_injectScriptTag: (scriptTag) -> | |
firstScriptTag = document.getElementsByTagName('script')[0] | |
firstScriptTag.parentNode.insertBefore scriptTag, firstScriptTag | |
@trackPageView: (url) -> | |
window._gaq.push ['_trackPageview', url] | |
@trackEvent: (category, action, label = null, value = null, nonInteraction = null) -> | |
trackedEvent = ['_trackEvent', category, action] | |
for argument in [label, value, nonInteraction] | |
if argument? then trackedEvent.push argument else break | |
window._gaq.push trackedEvent | |
# Assuming you're using jQuery to get up and going... | |
$ -> | |
# Replace the parameter to GoogleAnalytics.init with your Google Analytics | |
# web property ID. This tracks the initial page view. | |
GoogleAnalytics.init 'UA-1234567-8' | |
# Then later, if your user initiates another action that doesn't trigger a | |
# full page load, but that you wish to track as a page view (such as an AJAX | |
# request): | |
GoogleAnalytics.trackPageView '/myAjaxHandler' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment