How to prevent code execution when developing in Jekyll but displaying it in production. Avoid ads, analytics and disqus loading while developing.

Process

Current
sequenceDiagram local->>local: webpage loading starts local->>DisqusServer: javascript request DisqusServer-->>local: disqus code response local->>AnalyticsServer: javascript request local->>local: webpage ready
Goal
sequenceDiagram local->>local: webpage loading starts local->>local: webpage ready

Overview

While developing and continuously testing a jekyll site, avoiding any javascript external request can greatly improve the loading speed of each page.

In the case of advertisements, also prevents from accidentally clicking developer’s own ads which can cause an account suspension.

The basic concept to make it possible is to create different Jekyll builds for development and production environments.

Environment

The easiest way to avoid any external javascript request is to detect the environment on which Jekyll is running in liquid templates using the environment variable JEKYLL_ENV at build (or serve) time.

To build a production ready jekyll site it can be specified like this:

$ JEKYLL_ENV=production jekyll build

If none environment is explicitly set, then it uses by default JEKYLL_ENV=development

When using a Bundler command it should be used like:

$ JEKYLL_ENV=production bundle exec jekyll build

Detecting the environment in templates

To detect the environment in Jekyll liquid templates, jekyll.environment variable contains the current environment.

For example, to avoid showing post tags in development:

{% if jekyll.environment == "production" %}
 {{ post.tags }}
{% endif %}

Summary

graph TB template["Configure different workflows
for each environment"]; template ==> build{"build the site with
JEKYLL_ENV"}; build ==>|development| development["if JEKYLL_ENV=development won't load code"] build ==>|production| production["JEKYLL_ENV=production will load code"]
Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.