Tech for Retail 2025 Workshop: From SEO to GEO – Gaining Visibility in the Era of Generative Engines

Back to blog

How to Organise Containers and Scripts in Google Tag Manager

SEO

Discover Incremys

The 360° Next Gen SEO Platform

Request a demo
Last updated on

22/2/2026

Chapter 01

Example H2
Example H3
Example H4
Example H5
Example H6

If you already know the fundamentals of Google Tag Manager, this article zooms in on a specific area that often causes production issues: the Google Tag Manager script and, more broadly, how scripts and tags load, fire and can be diagnosed.

 

The Google Tag Manager Script: Deploy Tags Without Changing Your Code Every Time

 

The GTM script is used to load a container on your website so you can deploy and manage tags (measurement, conversions, advertising scripts, third-party pixels, custom HTML) without having to edit source code with every addition or change. The aim is not to "stack scripts", but to govern instrumentation that is testable, versioned and sustainable, while limiting duplication and regressions.

In practice, this script behaves like a loader: it initialises an entry point (notably via the dataLayer), then fetches your container configuration and executes tags based on your firing rules.

 

What This Article Goes Deeper Into (and Why)

 

The main guide already covers the architecture (container, tags, triggers, variables) and the overall deployment logic. Here, we focus on more technical, operational topics that determine real-world reliability:

  • what the snippet actually contains (asynchronous loading, src, noscript, dataLayer initialisation);
  • where to place the snippets (head vs body) and how this affects data collection, performance and compliance;
  • how to add bespoke JavaScript via a Custom HTML tag without creating duplicates;
  • how to diagnose situations where "it loads but nothing is tracked" (triggers, consent, CSP, cache, SPAs, ad blockers).

 

Is Google Tag Manager Still Used?

 

Yes. GTM remains the orchestration layer that decides when and under which conditions tags fire. Even though the "Google tag" refers to a unified tag on the Google side (GA4 or Ads), GTM keeps its governance role: versioning, environments, firing rules, variables, and reduced risk of double implementation.

 

How Does Tag Manager and Its Container Work?

 

A container groups tags together. Each tag performs an action (send a GA4 event, record a Google Ads conversion, load a third-party pixel, execute custom HTML/JS) and fires based on a rule. Variables feed those rules and tags with values (URL, identifiers, amounts, attributes taken from the Google Tag Manager data layer, and so on).

This logic has an important implication for scripts: the quality of your tracking depends less on "having pasted a snippet" and more on the stability of your signals (events, variables, consent, and the absence of duplicates).

 

Set Up GTM and Retrieve the Container Code: ID, Script, src and noscript

 

 

How Do You Set Up Google Tag Manager Cleanly?

 

Before you copy any code, put two simple guardrails in place:

  • one site = one container, named clearly (domain + environment);
  • one implementation source per tag: avoid keeping tracking hard-coded in the site while also reinstalling it via GTM (double-counted page views, events and conversions).

If you are at the "container installation" stage, the safest approach is to follow an implementation process tailored to your CMS or framework, then add tags progressively (GA4 first, conversions next, third-party pixels last). You can use our step-by-step guide to install Google Tag Manager.

 

How to Get the Code From the Interface (ID, Container Code and Settings)

 

In GTM, the container ID follows the format GTM-XXXXXXX. The interface provides two snippets: a <script> snippet and a <noscript> snippet. The key point is to take the code from the right container and the right environment (staging vs production), so you do not end up with crossed tracking between sites.

 

How Do You Retrieve the Script and the noscript Snippet Depending on Your Integration Context?

 

Your context dictates where and how to inject both snippets:

  • traditional website: add them to templates (header + immediately after the opening body tag) to ensure presence on all pages, including error pages;
  • CMS: use a dedicated header/body field or a controlled method (a reputable plugin, a child theme);
  • SPA / frameworks: inject once in the root layout, then handle route changes appropriately (virtual events) to avoid multiple firings.

 

What Exactly Is Inside the Snippet: Script Tag, src Attribute, Loading and noscript?

 

The implementation relies on two complementary elements:

  • the <script> snippet, the core loader, typically placed in the <head>;
  • the <noscript> snippet, a fallback via an <iframe>, typically placed immediately after the opening <body> tag for cases where JavaScript is disabled.

Example snippets (with a dummy ID):

<script async src='https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXX'></script><noscript><iframe src='https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX'></iframe></noscript>

Depending on the implementation, you may also see a fuller loader that initialises dataLayer and pushes gtm.start before loading gtm.js. This detail matters for troubleshooting (execution order, variable availability, "Initialization" triggers).

 

A Code Snippet Example Is Not Enough: What to Check Before You Publish

 

Even with a valid snippet, check the following before any release:

  • container ID (correct site and environment);
  • both snippets present (head + opening body);
  • no duplication (another GTM container, a GA4 tag hard-coded already, a plugin reinjecting code);
  • systematic testing using Preview mode (see the "Test and Validate" section).

 

Where to Place the GTM Script: Head vs Body and Placement Rules

 

 

Should the Snippet Go in the Head, the Body, or Both?

 

The most robust recommendation remains: the JavaScript snippet in the <head> (as high as possible) and the <noscript> snippet immediately after the opening <body> tag. This placement is designed to load the container early, reducing the risk of missing interactions if a user leaves quickly, particularly on mobile.

 

Placement by Goal: Performance, Tracking Reliability and Compliance

 

Placing the loader in the <head> makes it easier to execute critical tags early in the page lifecycle. There is also an indirect SEO consideration: a site perceived as slow can worsen the experience, increase bounce rate and reduce time on site.

On mobile, the impact is even clearer: Google indicates that 53% of visits are abandoned if a page takes more than 3 seconds to load (Google, 2025, cited in our SEO statistics). That does not mean GTM automatically "slows a site down"; rather, poorly governed script accumulation can harm user experience, which then affects business performance and SEO outcomes.

From a compliance standpoint, correct placement does not remove the key rule: certain tags (marketing, remarketing) should not fire before consent, which is why firing rules and Google Tag Manager cookies governance matter.

 

When Adding It to the Body Makes Sense, and the Firing Risks It Introduces

 

Adding the snippet in the body can be a practical compromise if your CMS does not allow injection into the head. The main risk is timing: loading later can cause you to miss early events (initial page_view, quick clicks, short-path conversions). Many implementation guides explicitly advise against placing the code just before </body>, as it delays collection.

Put simply: if you have to move it lower, compensate with more thorough testing and appropriately timed triggers (for example, "Initialization" for certain tags).

 

CMS and Framework Integrations: WordPress, Shopify and Next.js

 

 

WordPress: Add the Code Without Breaking Your Theme (or Your Cache)

 

On WordPress, the number one trap is editing a theme directly (changes get overwritten during updates). Prefer a child theme or a mechanism designed to inject code into the head and immediately after the opening body tag. Then check caching (plugin, server, CDN): aggressive caching can make it look as though your changes have not applied, or leave an old snippet active.

 

WordPress: Theme, Plugin or Controlled Injection?

 

The right approach depends on your governance model:

  • child theme: robust, but requires deployment discipline;
  • dedicated plugin: convenient, but needs auditing (risk of double insertion, additional tracking options);
  • controlled injection (hooks/precise placement): useful if you need environment-based conditions (staging vs production).

In all cases, watch for duplication: some analytics plugins already add GA4, which creates duplicates if you also deploy it through GTM.

 

Shopify: Implement Without Duplicates and Without Disrupting Checkout

 

On Shopify, the priority is to avoid inconsistent measurement between themes, apps and checkout. Check:

  • whether a marketing or analytics app already adds GTM or pixels in parallel;
  • whether your e-commerce events (add to basket, purchase) use a stable signal (ideally dataLayer) rather than fragile DOM selectors;
  • whether checkout has specific constraints depending on your plan and setup.

 

Next.js: Handle SPA Routing, Prevent Duplicates and Stabilise Triggers

 

With Next.js (or any SPA), the initial load does not represent subsequent navigations. Without adaptation, you risk:

  • missing page views (route changes are not measured);
  • multiple firings if a script is reinjected on every render;
  • URL-based triggers behaving differently depending on navigation mode.

A reliable approach is to track route changes via a stable application-level event (or a dataLayer strategy) and to make your scripts idempotent (see the "Add a Bespoke Script" section).

 

Tags, Triggers and Custom Events: GA4, Google Ads and Custom HTML

 

 

How to Choose Between a GA4 Tag, a Google Ads Tag, Custom HTML and Third-Party Pixels

 

Choose the tag based on your goal and the robustness of the signal:

  • GA4: measure behaviour and events (engagement, journeys, micro-actions);
  • Google Ads: conversions and remarketing (advertising attribution);
  • Custom HTML: non-native scripts, specific adjustments, controlled injection (to be tightly governed);
  • third-party pixels (e.g. the Meta pixel in Google Tag Manager): measurement and marketing activation on external platforms, often consent-dependent.

Keep responsibilities clear: GTM orchestrates; analytics tools (e.g. Google Analytics 4) analyse. This is exactly why understanding Google Tag Manager vs Google Analytics prevents common misconceptions.

 

GA4: Recommended Events vs Custom Events (Names, Parameters and Consistency)

 

A good measurement plan typically separates:

  • a base tag (Google tag / GA4) firing on all pages;
  • custom events describing business actions (lead_submit, demo_request, pricing_view...), enriched with stable parameters (form_name, content_type, funnel_stage...).

To avoid an unreadable container, enforce a taxonomy and keep parameters consistent (the same name should always carry the same meaning). This consistency is also what later allows you to link acquisition and behaviour cleanly across Google Tag Manager and Google Analytics.

 

Google Ads: Configure a Reliable Conversion Tag (De-duplication and Attribution)

 

A reliable Ads conversion starts with a robust signal: ideally a dataLayer event fired on true success (submission completed, purchase confirmed), rather than a simple page view. Common risks include:

  • false positives (a thank-you page reachable without a real action);
  • double counting (hard-coded conversion + conversion via GTM);
  • inconsistent attribution if parameters change across pages or environments.

If you are also managing campaigns, you can benchmark your results against our SEA statistics, without conflating Ads objectives with SEO measurement.

 

Custom HTML: Add JavaScript in a Controlled Way (Security, Performance and Compliance)

 

Custom HTML tags are powerful, but they are also where technical debt is created most easily (undocumented scripts, multiple listeners, uncontrolled third-party loading). Govern them with three rules:

  • security: avoid injecting unaudited code; account for CSP; keep scripts to what is strictly necessary;
  • performance: target firing (not "all pages" by default) and remove unused tags;
  • compliance: fire only after consent when the purpose requires it.

Note: GTM can also be used to inject JSON-LD occasionally via Custom HTML, but this must remain controlled and stable, and it does not replace proper work on structured data.

 

Add a Bespoke Script: Add JavaScript via Custom HTML and the Data Layer

 

 

How to Add JavaScript Properly: Idempotence, Listeners and Clean-up

 

When you add JavaScript through a Custom HTML tag, your goal is to prevent it from executing multiple times (a common issue in SPAs, or when a trigger replays). One simple principle: make your code idempotent.

A minimal example (marking a global state to avoid binding the same listener twice):

<script>window.__trackingDemoCtaBound = window.__trackingDemoCtaBound || false;if (!window.__trackingDemoCtaBound) { window.__trackingDemoCtaBound = true; document.addEventListener('click', function (e) { var btn = e.target.closest && e.target.closest('#demo-btn'); if (!btn) return; window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'demo_request_click', cta_location: 'header' }); }, { capture: true });}</script>

This pattern limits duplication without relying on a fragile page structure, as long as the element has a stable identifier.

 

Send Robust Data via the Data Layer for Stable Triggers

 

To fire tags cleanly (GA4, Ads, pixels) on a shared signal, the most robust approach is often to push an application event into the data layer and use it as the trigger in GTM.

Example push (successful form submission):

dataLayer.push({ event: "lead_submit", form_name: "demo", plan: "pro"});

Then in GTM:

  • create Data Layer Variables (form_name, plan);
  • create a Custom Event trigger for lead_submit;
  • fire a GA4 tag on that event and, if needed, an Ads tag or a third-party pixel.

 

Troubleshooting: Blocking, Not Working and "Refused to Load" Errors

 

 

Script Blocking: How to Diagnose a Block (CSP, Ad Blocker, Proxy)

 

Blocking can occur at several layers:

  • CSP (Content Security Policy) preventing googletagmanager.com from loading;
  • ad blockers (Preview mode may fail, or some requests may be filtered);
  • corporate proxies or networks blocking tracking domains;
  • consent deliberately preventing marketing tags from firing.

A good first step is to test in a private window and/or with extensions disabled, then use the Network tab (DevTools) to confirm whether gtm.js and ns.html load correctly.

 

"Refused to Load": What It Means and How to Fix It

 

This error usually means the browser refused to load a resource (script, iframe) due to a security policy (CSP), a network block, mixed content (HTTP/HTTPS) or filtering. To fix it:

  • identify the CSP directive involved and explicitly allow the required source (if compatible with your security policy);
  • ensure the site loads fully over HTTPS;
  • confirm www.googletagmanager.com is not blocked by a proxy or firewall.

 

Why GTM Loads but Tags Are Not Working: Triggers, Variables and Consent

 

Most often, the issue is not the snippet, but configuration:

  • trigger too restrictive (or firing at the wrong time);
  • variables not enabled or data layer variables misnamed (missing key, unexpected format);
  • consent preventing tag firing (expected behaviour, but it must be interpreted correctly in your comparisons).

For critical tags, firing earlier (e.g. "Initialization") may be necessary, but only if you understand the impact and compliance requirements.

 

Implementation Conflicts: Double Containers, Wrong Environment, CDN and Cache

 

Four recurring conflicts show up in audits:

  • double containers (two GTM IDs on the same page);
  • wrong environment (staging in production, or the other way around);
  • CDN or cache serving an older template version with a different snippet;
  • tags already present via a plugin or legacy hard-coded scripts.

 

Test and Validate: a Workflow Using Preview Mode and Network Debugging

 

Never validate "by feel". Use GTM Preview mode, then review:

  • which events show your tag under "Tags Fired" or "Tag not fired";
  • variable values at the moment of firing;
  • the actual network requests sent (GA4, Ads, pixels).

To formalise your QA process, you can also use our guide to test Google Tag Manager before publishing.

 

GTM Governance: Organisation, Quality and Maintenance

 

 

Naming Tags, Triggers and Variables: Simple, Durable Conventions

 

Naming is not cosmetic; it is what makes audits and troubleshooting fast. A pragmatic convention:

  • tags: GA4 - event - lead_submit, Ads - conversion - lead_submit, HTML - helper - demo_cta_listener;
  • triggers: CE - lead_submit, CLK - demo_btn;
  • variables: DLV - plan, CONST - currency.

 

Structure the Container: Folders, Versioning, Environments and Change Reviews

 

As the container grows, organisation prevents mistakes:

  • folders by purpose (analytics, ads, third-party pixels, HTML utilities, consent);
  • version descriptions completed on every publish (what, why, scope);
  • environment-based rollouts (staging then production), especially when multiple teams touch tracking.

 

Document the Implementation to Avoid Tracking Debt Across Teams

 

At minimum, document:

  • where the snippets are injected (files, modules, apps, theme, Shopify app, etc.);
  • which hard-coded tags still exist (and the migration plan);
  • your event taxonomy (names, parameters, expected formats);
  • consent rules applied to each tag category.

This is what prevents UX changes (redesigns, A/B tests) from silently breaking data collection.

 

GEO Angle: How Script-Based Tracking Affects Visibility in Generative AI Answers

 

 

What Remains Measurable: Attribution, Collection Limits and SEO/GEO Interpretation

 

The "zero-click" context and AI-generated answers complicate any reading based solely on sessions. Semrush (2025) reports that 60% of searches end without a click, and that traffic from AI search grew by +527% year on year (Semrush, 2025). This makes it even more important to instrument what happens after arrival: real engagement, visits to intent-driven pages and micro-conversions.

However, keep the limits in mind: some visitors block scripts, and compliance (consent) mechanically reduces observable volumes. The goal is not "100% of data"; it is stable, explainable data that remains comparable over time.

 

Connect Your Analysis: Google Analytics, GA4 and ROI-Led Dashboards

 

To steer SEO and GEO strategy, you need to connect two signal families: visibility (Search Console) and behaviour/conversion (GA4). Tag Manager simply delivers the data. The key is linking content pages, events (intent, value) and business outcomes, with a stable taxonomy and validated collection.

To frame broader trends and inform your hypotheses, you can cross-check your analysis with our GEO statistics.

 

Scaling GTM: Automation, API and Integration Processes

 

 

What to Manage: Accounts, Containers, Versions and Workspaces

 

As you multiply sites, environments and teams, standardisation becomes a priority. Automation typically covers container management, workspaces, versions and change traceability. To go further, the Google Tag Manager API helps structure these operations and reduce risky manual work.

 

Build an Integration Pipeline: Validation, Publishing and Traceability

 

A healthy delivery chain includes:

  • validation in staging (Preview mode, full user journeys, network checks);
  • versioned publishing (name + description);
  • a review step (at least for marketing tags and Custom HTML);
  • a rollback plan (restore a previous version if something goes wrong).

 

A Word on Incremys

 

 

Centralise Search Console and GA4, Then Connect Content, Tracking and ROI With a 360° SEO/GEO Approach

 

Incremys is a SaaS platform focused on editorial performance. It integrates Google Search Console and GA4 via API to connect visibility (queries, impressions, clicks) with behaviour (events, conversions) in a single unified view. The goal is to identify which content generates demand, which creates intent, and which truly contributes to ROI, without multiplying disconnected analyses.

 

FAQ: Scripts, Container Code, Integration and Troubleshooting

 

 

How Do I Retrieve the Script and Code Without Using the Wrong Container?

 

Always retrieve both snippets provided by the GTM interface (script + noscript) from the correct container for the correct site, then verify the ID (format GTM-XXXXXXX) in production code. If in doubt, use Preview mode and the Network tab to confirm that gtm.js loads with the correct ID.

 

What Does the Container Code Include: Script, src and noscript?

 

The main snippet loads https://www.googletagmanager.com/gtm.js?id=... (via the src attribute, asynchronously) and initialises tag firing. The <noscript> snippet adds an <iframe> pointing to https://www.googletagmanager.com/ns.html?id=... as a fallback when JavaScript is disabled.

 

Where Should I Place the Snippet, and When Should It Be Added in the Body?

 

Standard recommendation: put the script in the <head> (as high as possible) and the noscript immediately after the opening <body> tag. Putting the script in the body can help if your CMS restricts head access, but it increases the risk of late loading and missing early events.

 

Which Snippet Checks Help You Audit an Implementation Quickly?

 

At a minimum, verify the presence of gtm.js?id=GTM-... in the head and ns.html?id=GTM-... in the body. Then confirm the container connects in Preview mode and that at least one base tag (e.g. GA4) fires as expected.

 

How Can I Add JavaScript Without Causing Performance or Security Regressions?

 

Use Custom HTML only when necessary, make the code idempotent (no duplicate listeners), limit firing scope (targeted pages/events) and document the rationale. Monitor compliance (consent) and security policies (CSP).

 

What Should I Do if There Is Blocking, a Malfunction, or a "Refused to Load" Error?

 

Start by isolating the cause: (1) does the container load (Network)? (2) do tags fire (Preview)? (3) is an ad blocker, CSP or proxy blocking requests? (4) is consent intentionally preventing marketing tags from firing? Then fix the responsible layer (CSP, trigger, variable, cache, duplication).

 

WordPress: Which Method Should I Choose to Add the Code Without Plugin Conflicts?

 

Avoid editing the theme directly. Use a child theme or controlled injection. Audit your analytics and marketing plugins: many already inject GA4 or pixels, which creates duplicates if you deploy the same tags via GTM.

 

Shopify: What Should I Check to Avoid Duplicates at Checkout?

 

First, list all apps that inject pixels and tags. Then run a full purchase journey in Preview mode to verify firings, and ensure your conversions rely on a robust signal (a dataLayer event or equivalent), not only a page view.

 

Next.js: How Can I Prevent Multiple Firings During Route Changes?

 

Inject GTM once in the root layout, then track route changes with a dedicated strategy (virtual events or data layer pushes). For any JavaScript added via Custom HTML, apply idempotent logic so you do not bind the same listener multiple times.

To explore these topics further — SEO, GEO, tracking and data-driven methodology — visit the Incremys Blog.

Discover other items

See all

Next-gen GEO/SEO starts here

Complete the form so we can contact you.

The new generation of SEO
is on!

Thank you for your request, we will get back to you as soon as possible.

Oops! Something went wrong while submitting the form.