Can I use ng-include element to add my Google Analytics script?

68 views Asked by At

I have a partials/google-analytics.html and I would like to use ng-include to organize it.

index.html

<ng-include src="'partials/google-analytics.html'"></ng-include>

partials/google-analytics.html

<script>
(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', 'UA-XXXXXX-X', 'auto');
ga('send', 'pageview');

Does it work?

1

There are 1 answers

0
benjaminapetersen On

It will probably work, but its not ideal. GA suggests putting the code in the <head> before the closing </head>. This is to ensure it is loaded and evaluated before the user interacts with anything on your page. If you put it in a separate <ng-include>, that file will be loaded asynchronously and you run the risk of missing events.