0

I'm running into an issue and would appreciate some pointers. I have a production Django app where I included Google Analytics using a context processor and conditionally render it in my base.html template like this:

    <!-- Google Analytics -->
    {% if GOOGLE_ANALYTICS_ID %}
    <script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag() { dataLayer.push(arguments); }
        gtag('js', new Date());
        gtag('config', '{{ GOOGLE_ANALYTICS_ID }}');
    </script>
    {% endif %}
    <!-- End Google Analytics -->

Everything was working fine but the GA tracking completely breaks after enabling django_minify_html

These are my current settings:

For base.py:

USE_MINIFICATION = DJANGO_ENV == "production"
MINIFY_HTML = {
    "enabled": USE_MINIFICATION,
    "remove_comments": True,
    "minify_js": False,
    "minify_css": True,
}

For production.py

from .base import MIDDLEWARE as BASE_MIDDLEWARE

MIDDLEWARE = list(BASE_MIDDLEWARE)
# Insert MinifyHtmlMiddleware after WhiteNoiseMiddleware 
try:
    whitenoise_index = MIDDLEWARE.index("whitenoise.middleware.WhiteNoiseMiddleware")
    MIDDLEWARE.insert(whitenoise_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware")
except ValueError:
    try:
        security_index = MIDDLEWARE.index("django.middleware.security.SecurityMiddleware")
        MIDDLEWARE.insert(security_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware")
    except ValueError:
        MIDDLEWARE.insert(0, "django_minify_html.middleware.MinifyHtmlMiddleware")

Has anyone encountered this before? I've minify_js to False in hopes to exclude the GA script but keep on getting the console error.

Would love to hear any tips or workarounds for the best way to exclude GA tracking code from compression/minification.

Thanks!

4
  • What is MINIFY_HTML? django-minify-html doesn't have any configurable settings. Also what do you see in place of the GA code when you click View Source in the web browser? Commented Jun 16 at 3:52
  • @Selcuk I interpreted those settings from their documentation "By default the middleware overrides minify_css and minify_js to True. If you need to change an argument, subclass the middleware, replace minify_args, and use your subclass. For example, to preserve comments after minification:" When I look at the debug error this is what it says "<script>var gtag=(()=>{dataLayer.push(arguments)});window.dataLayer=window.dataLayer||[];gtag(js,new Date());gtag(config,G-MYVALUE_ASPER.ENV)</script>" Commented Jun 17 at 6:23
  • Those are arguments passed to the rust binary. They are not configurable via Django's settings.py (unless you make your own subclass and use it as the middleware as documented). Regarding the script tag: The error handler might have re-formatted the script tag. To make sure, use the View Source function of your browser and copy the GA script from the HTML. Don't post it as a comment as it becomes unreadable. Edit your question and add the extra information there, properly formatted. Commented Jun 18 at 0:17
  • 1
    @Selcuk Ahh I see what you mean and you are totally right. I though that I had to include it as an option in the base settings but will look into editing the middleware in production.py Thanks for the pointer mate! Commented Jun 18 at 22:48

1 Answer 1

0

Root of problem

The problem is that django_minify_html minifies your HTML, including Google analytics JavaScript code, even then minify_js=False is set.

How fix

  1. First ensure you are using latest version of file, try updating your django_minify_html with command pip install --upgrade django-minify-html.
  2. Wrap the code with <!-- !minify-html-preserve --> instead of <!-- Google Analytics --> it will tell django, to skip code between lines thats how to do it:
<!-- !minify-html-preserve -->
{% if GOOGLE_ANALYTICS_ID %}
<script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', '{{ GOOGLE_ANALYTICS_ID }}');
</script>
{% endif %}
<!-- !minify-html-preserve-end -->
  1. Also can try "verbatim" if the issue stayed:
{% if GOOGLE_ANALYTICS_ID %}
<script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script>
<script>
{% verbatim %}
   window.dataLayer = window.dataLayer || [];
   function gtag() { dataLayer.push(arguments); }
   gtag('js', new Date());
   gtag('config', '{{ GOOGLE_ANALYTICS_ID }}');
{% endverbatim %}
</script>
{% endif %}

Test each solution, to see, which solution resolves the issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.