Django-minify-html breaks Google Analytics injection

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!

Вернуться на верх