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

Back to blog

Google Tag Manager script: deploying tags without changing your code

SEO

Discover Incremys

The 360° Next Gen SEO Platform

Request a demo
Last updated on

1/11/2026

Chapter 01

Example H2
Example H3
Example H4
Example H5
Example H6

This page is for the marketing manager, SEO specialist or analyst who needs tags to load cleanly on a site without redeploying code with every change. It covers the official Google Tag Manager script, tag types, bespoke JavaScript and third-party scripts.

 

You will know which tag to choose, how to write a script that runs only once, how to name items in a container and where to look when a script refuses to load.

 

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

 

The Google Tag Manager script loads a container, then executes its tags based on your firing rules: GA4 measurement, third-party pixels, custom HTML. The aim is not to "stack scripts", but to govern instrumentation that is testable and versioned.

 

The fundamentals are set out in our complete Google Tag Manager guide; here, we focus on scripts and how they load.

 

Is GTM still used? Yes. The Google tag has unified gtag.js since 2022, and in GTM the "Google Tag" tag replaced the "GA4 Configuration" tag in September 2023, at the time of writing. GTM still decides when each tag fires.

 

How Does Tag Manager and Its Container Work?

 

GTM is organised into four levels, from the broadest to the most granular:

 

  • account: the company or organisation;
  • container: one site, identified by its ID;
  • workspace: drafts in progress, invisible to visitors;
  • published version: the only configuration actually served.

 

Each tag performs an action based on a trigger, and variables feed it with values. The quality of your tracking therefore depends far more on the stability of these signals than on the snippet.

 

Retrieve the Container Code: ID, Script, src and noscript

 

The container ID follows the format GTM-XXXXXXX. The snippet has two parts: the script, placed as high as possible in the <head>, and the <noscript> with an iframe, immediately after the opening <body> tag. Here is the official snippet, with a dummy ID:

 

<!-- Google Tag Manager -->

 

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':

 

new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],

 

j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=

 

'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);

 

})(window,document,'script','dataLayer','GTM-XXXXXXX');</script>

 

<!-- End Google Tag Manager -->

 

<!-- Google Tag Manager (noscript) -->

 

<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"

 

height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>

 

<!-- End Google Tag Manager (noscript) -->

 

The script initialises window.dataLayer, pushes the gtm.js event with the gtm.start timestamp, then loads gtm.js asynchronously. Do not copy a shortened version: without this initialisation, execution order and variable availability become unpredictable.

 

The <noscript> only matters when JavaScript is disabled: only a "Custom Image" tag can then fire, with no data layer and no CMP. Placement by CMS and the installation checklist are covered in our guide to install Google Tag Manager on your site.

 

A Code Snippet Example: What to Check Before You Publish

 

A valid snippet does not guarantee clean data collection. Before any release, check the following:

 

  • container ID: the one for the correct site and environment, to avoid crossed tracking between staging and production;
  • both parts present: script in the <head>, <noscript> after the opening <body> tag, on every page template;
  • no second container: two GTM IDs on the same page double the firings;
  • no redundant hard-coded tag: a gtag.js coded into the theme or reinjected by a plugin double-counts page views;
  • one site per container, named clearly (domain and environment).

 

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

 

The technical context dictates where to inject both parts and which duplicates to watch for. Three cases come up repeatedly:

 

  • WordPress: use a child theme, an audited plugin or controlled, environment-based injection, never the parent theme, whose changes are overwritten during updates;
  • Shopify: with Checkout Extensibility, GTM is no longer accepted in checkout, at the time of writing; purchase events go through custom pixels;
  • Next.js: load GTM only once in the root layout and track route changes with an event pushed to the data layer.

 

On WordPress, also watch caching, which can serve an old snippet, and analytics plugins that already reinject GA4: every page view would be counted twice. On Shopify, likewise list the apps that add their own pixels.

 

Tags, Triggers and Custom Events: GA4, Templates and Custom HTML

 

The choice of tag depends on your goal and the robustness of the signal. GTM fires and sends; the analytics tool receives and reports: our comparison of Google Tag Manager vs Google Analytics details this split.

 

How to Choose Between the Google Tag, a GA4 Event, a Template and Custom HTML

 

Five tag types cover most needs. The table shows what each is used for and the risk to watch:

 

Tag typeUseRisk
Google TagLoad GA4 on every page, send page_viewDuplicate with a hard-coded gtag.js
GA4 Event tagSend a business action and its parametersInconsistent event names from one tag to another
Community Template Gallery templateIntegrate a third-party tool without writing codeThird-party template to audit before use
Custom HTML tagNon-native script, bespoke listenerDouble execution, technical debt, CSP blocking
Custom Image tagImage pixel, the only tag that can fire without JavaScriptNo data from the data layer or the CMP

 

Prefer a native tag or a template over custom HTML: the code is maintained by the vendor. Custom HTML is justified when no template covers the need.

 

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

 

A measurement plan separates the Google Tag, which already sends page_view, from custom events describing business actions (lead_submit, demo_request), enriched with stable parameters such as form_name or content_type.

 

The same parameter name should always carry the same meaning. GA4 Event tags, enhanced measurement and key events are covered in our tutorial to set up GA4 with Google Tag Manager.

 

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

 

The custom HTML tag is powerful, but it is where most technical debt is created: undocumented scripts, multiple listeners, uncontrolled third-party loading. Govern it with three rules:

 

  • security: inject only audited code, limited to what is necessary and compatible with the site's CSP;
  • performance: fire on a targeted scope rather than "all pages" and remove unused tags;
  • compliance: make firing conditional on consent whenever the purpose requires it.

 

Injecting JSON-LD through a custom HTML tag is possible but not recommended: the markup then depends on JavaScript. Serve it in the page code, as explained in our guide to structured data.

 

Add a Bespoke Script via a Custom HTML Tag and the Data Layer

 

A script added through a custom HTML tag can execute several times, in an SPA or when a trigger replays. Make it idempotent, then rely on the data layer.

 

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

 

The principle: mark a global state the first time and do nothing afterwards. The following example binds a single click listener to a demo button, however many times it fires:

 

<script>

 

if (!window.__demoCtaBound) {

 

window.__demoCtaBound = 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 prevents duplicates as long as the element has a stable identifier. Bound to the document rather than the button, the listener survives SPA re-renders; the line window.dataLayer = window.dataLayer || [] covers a data layer that is not yet initialised.

 

Send Robust Data via the Data Layer for Stable Triggers

 

To fire several tags on the same signal, the site pushes an event into the data layer on true success of the action, for example lead_submit with form_name and plan (push syntax in our article on the Google Tag Manager data layer). In GTM, three steps follow:

 

  • create Data Layer Variables for form_name and plan;
  • create a Custom Event trigger for lead_submit;
  • attach the GA4 Event tag and, if needed, a third-party pixel to this trigger.

 

Third-Party Scripts: Gallery Template or Custom HTML?

 

Live chat, A/B testing, pixel, video: every third-party script raises a question of method and consent. Here are the default choices:

 

Third-party scriptMethodConsent requiredPitfall
Live chatTemplate, otherwise custom HTMLYes if it sets cookiesLoaded on every page by default
A/B testing toolCustom HTML, fired earlyYes for measurement cookiesA variant that breaks trigger selectors
Advertising pixel (Meta Pixel)Community Template Gallery templateYes, advertising purposeDoes not read Google's Consent Mode
Embedded video playerTemplate, otherwise custom HTMLYes if the player sets cookiesListener bound twice in an SPA

 

The consent condition is set once in GTM, through the CMP and exception triggers or trigger groups: the method is in our article on cookies and consent in Google Tag Manager.

 

Troubleshooting: Blocking, Silent Tags and "Refused to Load" Errors

 

When a script produces nothing, either the browser did not load the resource or the tag did not fire. Start with the Network tab in the developer tools: does gtm.js appear with the correct ID?

 

Script Blocking and the "Refused to Load" Error: What Does It Mean?

 

This message indicates that the browser refused a resource (script, iframe, request). The usual causes are:

 

  • CSP: the security policy does not allow www.googletagmanager.com or the analytics domains;
  • mixed content: a resource requested over HTTP on an HTTPS page;
  • ad blocker: an extension that filters requests, including in Preview mode;
  • corporate proxy or firewall: measurement domains blocked on the network.

 

Test in a private window first. If the CSP is blocking, allow the right domains and use the nonce-aware snippet; custom JavaScript variables require 'unsafe-eval'. The exact directives are in our Google Tag Manager CSP guide.

 

Why GTM Loads but Tags Do Not Fire

 

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

 

  • trigger too restrictive or evaluated at the wrong time;
  • misnamed data layer variable: missing key, unexpected format, path items[0] instead of items.0.item_id;
  • consent refused: the tag does not fire, which is the expected behaviour;
  • wrong environment: staging container loaded in production, or the other way around;
  • cache or CDN serving an older page template with an old snippet.

 

Check each hypothesis in Tag Assistant Preview mode, then in DebugView, following our method to test Google Tag Manager every time you publish a version.

 

GTM Governance: Organisation, Quality and Maintenance

 

A container without rules quickly becomes unreadable. Three levers prevent this drift: naming, folders and versions, documentation.

 

Naming Tags, Triggers and Variables: Simple, Durable Conventions

 

Naming makes audits and troubleshooting fast. Each name combines a prefix by object type, then the nature and the event, separated by "-":

 

ObjectPrefixExample
GA4 Event tagGA4GA4 - event - lead_submit
Custom HTML tagHTMLHTML - helper - demo_cta_listener
Custom Event triggerCECE - lead_submit
Click triggerCLKCLK - demo_btn
Data Layer VariableDLVDLV - plan
ConstantCONSTCONST - currency

 

The event name stays identical in the data layer, the trigger and the tag: CE - lead_submit immediately identifies the tag it feeds. Apply the same convention across all your containers.

 

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

 

As the container grows, its organisation prevents mistakes. Apply four rules:

 

  • folders by purpose: analytics, third-party pixels, HTML utilities, consent;
  • described versions: on every publish, a name and a description (what, why, scope);
  • environments: staging then production, especially when multiple teams touch measurement;
  • shared documentation: where snippets are injected, tags still hard-coded, event taxonomy, consent rules by category.

 

Scaling GTM: Automation, API and Integration Processes

 

As sites and teams multiply, the GTM API manages containers, workspaces and versions. Short of that, a healthy integration pipeline has four steps:

 

  • validation in staging: Preview mode, full user journey, network request checks;
  • a review by a second person, at least for custom HTML tags and third-party pixels;
  • versioned publishing, with a name and description;
  • a rollback plan: restoring a previous version if something goes wrong.

 

Depending on Your Situation

 

Depending on where you are, here is where to go next:

 

  • You are adding an advertising pixel: template setup, standard events and consent are detailed for the Meta Pixel in Google Tag Manager.
  • You are migrating a hard-coded gtag.js: remove it before enabling the Google Tag, using our guide to Google Analytics 4.
  • Your pages have slowed down since adding third-party scripts: measure their weight in a technical SEO audit before adding any more.

 

Once collection is stable, the Incremys performance reporting module brings Google Search Console and GA4 together to identify the pages that generate key events.

 

FAQ: Scripts, Container Code, Integration and Troubleshooting

 

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

 

Always copy both parts of the snippet from the container for the correct site and environment. Then verify that the ID in GTM-XXXXXXX format live in production is the right one. If in doubt, the Network tab shows which ID gtm.js actually loads.

 

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

 

The container code contains a script and a noscript block: the script initialises the data layer, pushes the gtm.js event, then loads gtm.js asynchronously via the src attribute. The noscript adds an iframe pointing to ns.html, useful only without JavaScript, when only a Custom Image tag can fire.

 

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

 

Add JavaScript through a custom HTML tag only when no template covers the need. Make the code idempotent so the same listener is never bound twice, fire it on a restricted scope, check its compatibility with the CSP and make it conditional on consent if its purpose requires it.

 

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

 

First isolate the layer at fault: loading, firing or consent. The Network tab shows whether gtm.js loads, and Preview mode whether the tag fires. A "refused to load" error comes from a CSP, mixed content, an ad blocker or a proxy.

 

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

 

On WordPress, add the code through a child theme or controlled injection, never in the parent theme. Audit your analytics plugins: many already reinject GA4 or pixels, which double-counts measurements if GTM deploys the same tags. Clear the cache after every change.

 

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

 

On Shopify, GTM is no longer accepted in checkout with Checkout Extensibility, at the time of writing: purchase events go through custom pixels. List the apps that inject their own pixels, then test a full purchase to confirm that no purchase is sent twice.

 

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

 

With Next.js, load GTM only once in the root layout and track each route change with an event pushed to the data layer. Any JavaScript added via custom HTML must be idempotent, so that a listener is never bound twice.

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.