Adding Google Analytics to Jekyll Site
Adding Google Analytics to your Jekyll site is a “Hello, world” excercise.
If you don’t bother about the manual implementation, minima, which is a default theme for new Jekyll sites, already contains this integration. The include for Google Analytics is added to the
default.html layout and thus applies to all site’s pages. To enable it, you need to add
google_analytics variable in your
_config.yml file, and specify your Google Tracking ID.
You might want to read further to find out how my implementation compares to the standard one. You can check the complete code in the repository.
Implementing Google Analytics Integration
Google Tracking code is specified in the
_config.yml file in the
google_analytics variable. It is used later by the include.
google-analytics.html contains a description on how to use the include and what are expected parameters. Description is done with a liquid
comment tag, so it does not affect the final HTML.
Here’s the code for the include:
There are two checks in the include that control the rendering. First one checks for the
google_analytics variable in the
_config.yml. If it’s not defined, final pages will contain HTML comment about it, and the script for integration will be skipped.
Second check is for the Jekyll environment. Integration script is rendered only when
jekyll.environment variable is equal to “production”. Otherwise, the HTML comment with a warning will be rendered.
If your site is hosted and rendered by GitHub Pages, “production” value will be used by GitHub during the rendering, so you don’t have to do anything.
When working with Jekyll locally, this value can be set when running Jekyll build. By default, local Jekyll will have
jekyll.environment equal to “development”.
Adding these checks makes the rendering process more transparent. I can always check the source of a page, and define whether all my configuration is in the right place.