How to use google analytics from jade file

Instead of having it look for another code file and load it. Inline (like Trevor suggested is better).

In order to accomplish this you have to make use of the script. tag.... not just script

See below:

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','//www.google-analytics.com/analytics.js','ga');

            ga('create', 'UA-11111111-1', 'yourdomain.com');
            ga('send', 'pageview');

Make sure the spacing and such is actually indented one tab from your stuff


As said here before - putting the GA snippet inline in your files is recommended, as the GA snippet will actually call another file (www.google-analytics.com/analytics.js), so it's a bit of a waste to GET another js file which will then GET the Google one.

However - if you do want to keep your layout.jade clean (and you should), you can put the code snippet BRogers wrote (the one that starts with "script.") , in a separate file, call it googleAnalytics.jade, and in your layout.jade just include :

include partials/googleAnalytics

(of course partials is the way I folder my views, that's up to you)

This will mean the GA snippet will be included in your pages on the server, saving you the additional GET, but still keeping your layout.jade nice and tidy.


The solution was easy.

Step 1: i created a file called 'analytics.js' and placed the code between the script tags in it. No conversion to jade syntax needed.

Step 2: i referenced the script from the jade file

script(src='/js/analytics.js')