diff --git a/pydata_sphinx_theme/__init__.py b/pydata_sphinx_theme/__init__.py
index a2b73492b..f913affca 100644
--- a/pydata_sphinx_theme/__init__.py
+++ b/pydata_sphinx_theme/__init__.py
@@ -268,6 +268,7 @@ def generate_google_analytics_script(id):
"""
diff --git a/pydata_sphinx_theme/layout.html b/pydata_sphinx_theme/layout.html
index e9e57f370..6284e384b 100644
--- a/pydata_sphinx_theme/layout.html
+++ b/pydata_sphinx_theme/layout.html
@@ -31,6 +31,9 @@
{% endif %}
{% endfor %}
+
+
+ {{ generate_google_analytics_script(id=theme_google_analytics_id) }}
{%- endblock %}
{# Silence the sidebar's, relbar's #}
@@ -105,7 +108,6 @@
{%- block scripts_end %}
{{ _webpack.body_post() }}
- {{ generate_google_analytics_script(id=theme_google_analytics_id) }}
{%- endblock %}
{%- endblock %}
diff --git a/tests/test_build.py b/tests/test_build.py
index 04142cfac..0881aa9ce 100644
--- a/tests/test_build.py
+++ b/tests/test_build.py
@@ -390,8 +390,8 @@ def test_new_google_analytics_id(sphinx_build_factory):
sphinx_build.build()
index_html = sphinx_build.html_tree("index.html")
# This text makes the assumption that the google analytics will always be
- # the last script tag found in the document.
- script_tag = index_html.select("script")[-1]
+ # the second last script tag found in the document (last is the theme js).
+ script_tag = index_html.select("script")[-2]
assert "gtag" in script_tag.string
assert "G-XXXXX" in script_tag.string
@@ -403,8 +403,8 @@ def test_old_google_analytics_id(sphinx_build_factory):
sphinx_build.build()
index_html = sphinx_build.html_tree("index.html")
# This text makes the assumption that the google analytics will always be
- # the one before last script tag found in the document.
- script_tag = index_html.select("script")[-1]
+ # the second last script tag found in the document (last is the theme js).
+ script_tag = index_html.select("script")[-2]
assert "ga" in script_tag.string
assert "UA-XXXXX" in script_tag.string