How to use Google Analytics in a Sphinx project


I no longer advise to use Google Analytics, and I have entirely removed it from my webpages, and I will no longer update these tutorials. As they would still be available from Google Cache or websites, I prefer to keep this page online.


This short page is focusing on Google Analytics

For more information, it might be useful to consult first one of these pages:


This short page is also focusing on Sphinx

Therefore, for more information, it might be useful to have in mind how Sphinx works, and in particular how to use HTML templating support

« Vanilla » Google Analytics code

The default code to add in every page is the following piece of JavaScript:

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
ga('create', 'UA-38514290-15', '');
ga('send', 'pageview');

The first and intuitive solution is, of course, to modify the main template document (usually, it should be _templates/layout.html ou .templates/layout.html) and to add it this code, between two tags <script type="text/javascript"> and </script>.

If possible, you have to add this piece of code at the end of the page, to reduce the page’s loading time.

A smaller piece of code

(And also easier to maintain !) You just have to create a small ga.js script contenaning the previous piece of code, and add it somewhere on your website.

For instance: ga.js.

Then you have to load it in every webpage with one-line of HTML code at the end of the file (in the <bottom> paragraph or at the end of <body>) :

<script type="text/javascript" async src=""></script>

Moreover, the async tag will improve the speed of the page, by loading asynchronously the ga.js script. Awesome!

How and where adding it

For example, you can take a look at my layout.html.

Other solutions ?

Sphinx has an extension for Google Analytics, see on the list of extensions here (this folder of the sphinx-contrib repository). It’s quick and simple, and working well, and for example I am using it for small Sphinx projects, see for examples: infoMP/TPs/solution, infoMP/DSs/solution and infoMP/TDs/solution.

Voir aussi

GA-Beacon (beacon.html)

How to use a one-pixel image to use Google Analytics to measure the audience of a page, or an email.

Statistics for Google Analytics (stats-google-analytics.en.html)

A small sum-up of the use of Google Analytics on this website (from the last 3 years), and some plots to illustrate the visits and visitors this website got.