Ad code & integration

AdSense in single-page apps: pushing ad slots on route changes without breaking policy

Last updated Published By the editorial team6 min6 sources

Key takeaways

  • Each adsbygoogle.push({}) call asks the AdSense library to fill one ins element that has not been filled yet; a filled ins is never filled a second time.
  • When no empty slot remains, the library throws the error "All 'ins' elements in the DOM with class=adsbygoogle already have ads in them."
  • In a single-page app, a route change must render a new ins element (for example by keying it on the route) before pushing again.
  • Google's ad placement policies forbid refreshing a page or an element of a page without the user requesting a refresh, so never re-request ads on a timer.
  • Google does not document how Auto ads behave across client-side route changes, so do not count on Auto ads re-analyzing each virtual page.
People looking at their smartphones on a railway station platform
Image: Smartphone use at railway station,Rawpixel.com,CC0,via Wikimedia Commons.

In a single-page app, load the AdSense code once, and after each route change render a new <ins class="adsbygoogle"> element and call adsbygoogle.push({}) once for it. A filled <ins> is never filled again, so reusing the old element does nothing. Never re-request ads without a user navigation, because AdSense policy forbids refreshing ads the user did not ask for.

How does adsbygoogle work under the hood?

Google’s ad unit code has three parts (Where to place ad unit code in your HTML):

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-0000000000000000"
     crossorigin="anonymous"></script>
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-0000000000000000"
     data-ad-slot="1234567890"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
  1. The library script loads once per document.
  2. The <ins> element is the slot.
  3. push({}) queues a request. If the library has not loaded yet, window.adsbygoogle is a plain array that the library processes when it arrives.

Each push fills one <ins> that has not been processed. After processing, the library marks the element with a data-adsbygoogle-status attribute (Google mentions it as used “for ads processing purposes”). If you push and no unprocessed <ins> is left, the library throws: “adsbygoogle.push() error: All ‘ins’ elements in the DOM with class=adsbygoogle already have ads in them.”

In a multi-page site this never matters: every page load brings fresh elements. In a single-page app, three things break the model:

  • Inline <script> tags inside components do not run like they do in static HTML, so the push must happen in component code.
  • Route changes do not reload the document. Elements in persistent layouts (header, sidebar) survive navigation, already filled.
  • Development tools such as React Strict Mode run effects twice, which pushes twice for one slot.

What is the generic pattern?

  1. Put the AdSense code in the HTML shell (index.html) <head>, once.
  2. Render the <ins> from a component.
  3. When the component mounts, push once.
  4. When the route changes and you want a new ad in a persistent area, replace the <ins> element (not just its attributes) and push once for the new element.
  5. Never push on timers, scroll events, visibility changes or focus.

A framework-agnostic helper that pushes only for slots it has not seen:

// ads.js
const seen = new WeakSet();

export function fillNewAdSlots(root = document) {
  root.querySelectorAll("ins.adsbygoogle").forEach((ins) => {
    if (seen.has(ins) || ins.hasAttribute("data-adsbygoogle-status")) return;
    seen.add(ins);
    try {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch (err) {
      console.error(err);
    }
  });
}

Call it after the router has rendered the new view. The WeakSet protects against double pushes before the library has had time to mark the element.

React (with React Router)

React Router’s useLocation docs show exactly this use: run a side effect “whenever it changes”. Key the <ins> on the path so a new element is created on navigation.

// AdUnit.jsx
import { useEffect, useRef } from "react";
import { useLocation } from "react-router";

export default function AdUnit({ adSlot }) {
  const { pathname } = useLocation();
  const pushedFor = useRef(null);

  useEffect(() => {
    if (pushedFor.current === pathname) return; // Strict Mode double run
    pushedFor.current = pathname;
    try {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch (err) {
      console.error(err);
    }
  }, [pathname]);

  return (
    <div style={{ minHeight: 280 }}>
      <ins
        key={pathname}
        className="adsbygoogle"
        style={{ display: "block" }}
        data-ad-client="ca-pub-0000000000000000"
        data-ad-slot={adSlot}
        data-ad-format="auto"
        data-full-width-responsive="true"
      />
    </div>
  );
}

The useEffect reference explains that in development Strict Mode runs “one extra development-only setup+cleanup cycle”; the ref guard absorbs it. For Next.js specifics (layouts, next/script), see AdSense in Next.js.

Vue 3 (with Vue Router)

Vue’s key attribute can “force replacement of an element/component instead of reusing it” (Vue built-in special attributes). Key the component on the route, and push in onMounted.

<!-- AdUnit.vue -->
<script setup>
import { onMounted } from "vue";
const props = defineProps({ adSlot: { type: String, required: true } });

onMounted(() => {
  try {
    (window.adsbygoogle = window.adsbygoogle || []).push({});
  } catch (err) {
    console.error(err);
  }
});
</script>

<template>
  <div style="min-height: 280px">
    <ins
      class="adsbygoogle"
      style="display: block"
      data-ad-client="ca-pub-0000000000000000"
      :data-ad-slot="props.adSlot"
      data-ad-format="auto"
      data-full-width-responsive="true"
    ></ins>
  </div>
</template>

In a persistent layout:

<AdUnit :key="$route.path" ad-slot="1234567890" />

When the path changes, Vue destroys the old component and mounts a new one, which creates a new <ins> and pushes once.

Svelte 5 (with SvelteKit)

Svelte’s {#key} block destroys and recreates its contents “when the value of an expression changes” (Svelte key blocks). onMount runs when the component is mounted and does not run during server rendering.

<!-- AdUnit.svelte -->
<script>
  import { onMount } from "svelte";
  let { adSlot } = $props();

  onMount(() => {
    try {
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    } catch (err) {
      console.error(err);
    }
  });
</script>

<div style="min-height: 280px">
  <ins
    class="adsbygoogle"
    style="display:block"
    data-ad-client="ca-pub-0000000000000000"
    data-ad-slot={adSlot}
    data-ad-format="auto"
    data-full-width-responsive="true"
  ></ins>
</div>

In +layout.svelte:

<script>
  import { page } from "$app/state";
  import AdUnit from "$lib/AdUnit.svelte";
  let { children } = $props();
</script>

{@render children()}

{#key page.url.pathname}
  <AdUnit adSlot="1234567890" />
{/key}

If you prefer one central hook, SvelteKit’s afterNavigate “runs the supplied callback when the current component mounts, and also whenever we navigate to a URL”, which is a good place to call fillNewAdSlots().

Where is the policy line?

Google does not publish SPA-specific AdSense rules, so you have to apply the general ones:

  • No unrequested refresh. The ad placement policies say publishers may not “refresh a page or an element of a page without the user requesting a refresh”. Pushing a new slot because the user navigated to a new view is driven by the user. Swapping ads every 30 seconds, on scroll, or when a tab regains focus is not.
  • Content must be evaluable. The same policy page warns that Google may disable ad serving on “content that we cannot evaluate”, for example content blocked by robots.txt or behind a login. Give each view a real URL, and prefer server rendering or prerendering so the content exists in the HTML.
  • No ads on screens without content. Loading states, empty search results and blank shells should not carry ad slots. Render the <ins> only once the view’s content is there.
  • Keep the code intact. The code modification policy forbids changes that artificially inflate ad performance. Moving the push call into a lifecycle hook does not change how ads are delivered; reloading slots to multiply impressions would.

What about Auto ads?

Auto ads use one piece of code and “scan your site” to place ads based on page structure (About Auto ads). Google’s documentation describes this for pages, and does not say whether Auto ads re-analyze the DOM after a client-side route change. Treat Auto ads in an SPA as a first-view feature unless your own reports show otherwise. If overlay formats such as anchors and vignettes matter to you, a framework mode that performs real page loads (server rendering with standard links) is the safer architecture. The Auto ads vs manual units guide compares both approaches.

Vignettes deserve a specific check. Google says that by default they “appear when a user clicks on a link on your site”, between page loads. A router link that never loads a new page may behave differently from a normal link, and Google does not document that case. Test your navigation with vignettes on, and if a link should never trigger one (a login, a checkout step), add Google’s documented data-google-vignette="false" attribute to that <a> element; see Prevent a link on your site from triggering vignette ads.

Troubleshooting

Symptom Cause Fix
“All ‘ins’ elements … already have ads in them.” More pushes than new slots One push per new <ins>; guard with a ref or WeakSet
“No slot size for availableWidth=0” Slot pushed while hidden or before layout (inside a closed tab, a modal, display:none) Push only when the slot is visible and has a width
Ad visible on first view, blank after navigation Persistent layout keeps the filled <ins> Key the element or component on the route
Unfilled blank boxes No ad returned Style unfilled slots with data-ad-status; see unfilled ad slots

Frequently asked questions

Is it allowed to load new AdSense ads when the route changes in a single-page app?

Google's policies do not mention single-page apps by name. What they forbid is refreshing a page or an element of a page without the user requesting it. Rendering a new ad slot because the user clicked through to new content behaves like a new page view. Re-requesting ads on a timer, on scroll or while the same content stays on screen does not, and risks a violation.

Why do I get "All 'ins' elements in the DOM with class=adsbygoogle already have ads in them"?

You called adsbygoogle.push more times than there are empty ins elements. Typical causes are React Strict Mode running effects twice in development, a component re-rendering and pushing again, or a persistent layout whose ins element was filled on the first route. Push once per newly created ins and give the element a key tied to the route.

Do Auto ads work in a React or Vue single-page app?

Auto ads load with the AdSense code and analyze the page they find. Google does not document whether they re-analyze content after client-side navigation, so behaviour across virtual pages is not guaranteed. If Auto ads are important to you, consider server-rendered or prerendered pages with real page loads, or test carefully and judge by your reports.

Can AdSense review a site that renders all content with JavaScript?

Google's placement policies say it may disable ad serving on content it cannot evaluate. Google does not publish details of how its review crawler renders JavaScript apps. To reduce risk, serve meaningful HTML for each URL through server rendering or prerendering, give every view its own URL, and make sure robots.txt does not block scripts or content.

Sources

  1. Where to place ad unit code in your HTML · Google AdSense Help
  2. Ad placement policies · Google AdSense Help
  3. About Auto ads · Google AdSense Help
  4. useEffect · React
  5. Built-in Special Attributes (key) · Vue.js
  6. $app/navigation · SvelteKit Docs