Refreshing Ads JavaScript and Ad Placements with NextJS Navigation

My NextJS website utilizes a custom JavaScript provided by an ad provider for running ads. The script is typically structured like this:

<script type="text/javascript" src="//cdn.adsite.com/static/js/ad.js" ></script>

In addition to the script, I place div tags on the webpage to serve as ad slots:

<div id="ad-tag-6098" ></div>
<div id="ad-tag-6099" ></div>
<div id="ad-tag-6076" ></div>

These div tags correspond to different ad slots on the page and are filled with ads using the JavaScript.

While this setup functions correctly on initial page loads or reloads, it fails to display ads when navigating internally through the router.

I am seeking guidance on how to properly reload the ad.js script to ensure that the ad slots display content accurately and refresh appropriately even during navigation using the NextJS router.

UPDATE: I have discovered a more complex issue related to the functioning of these ad slots. Simply reloading the JavaScript is insufficient. Due to the nature of these slots, transitioning between pages causes them to be stored in memory, leading to errors as the script recognizes them as already displayed.

The desired functionality should involve:

  1. Rendering the ad slot component, defining it, and displaying the ad,
  2. Removing all defined slots from memory upon route changes,
  3. Upon visiting a new page, allowing ad components to define and display fresh slots.

Answer №1

Just a friendly reminder, there are listeners in NextJS for route changes

  router.events.on('routeChangeComplete', handleRouteChange)
  router.events.off('routeChangeComplete', handleRouteChange)

You can dynamically reload scripts when the route changes using these events. By fetching and appending the script at the end of the body on every route change, you can effectively refresh the memory of the ads.

Hope this tip about router events is helpful for you. Looking forward to your feedback.

UPDATE: Based on your comment, I have an update. The router.events provide control over DOM manipulation. It doesn't have to be tied specifically to React or NextJS. Utilize the power of JavaScript.

If you are responsible for adding all ad divs, consider adding a data attribute to easily select them later.

For instance, Let's say you initially added this ad div

<div id="ad-tag-6098" ></div> // Instead of this!
<div id="ad-tag-6098" data-ad="true" ></div> // Add this one!

By utilizing the routeChangeStart event from router.events, you can identify the divs with the data-ad attribute and clear their content from the DOM before the routeChangeComplete event triggers. This way, when the script is reloaded, it won't cause errors.

const adDivs = document.querySelectorAll('[data-ad="true"]'); // Select these divs and remove their contents before the routeChangeComplete cycle

What are your thoughts on this updated part of my response? Feel free to share your insights.

Answer №2

One simple trick to reload a script repeatedly is by adding a unique query string each time.

To remove old advertisements, you can utilize the Script component's onLoad event handler. (Source: Next.js Docs)

import Script from 'next/script'

export default function Home() {
  const unique_id = new Date().getTime();
  return (
    <>
      <Script
        id={unique_id}
        src={`//cdn.adsite.com/static/js/ad.js?v=${unique_id}`}
        onLoad={() => {
          // code to execute after script loads
        }}
      />
    </>
  )
}


A more efficient approach would be to load the script only once, and then refresh or clear the existing ad slots as needed.

function refreshAllSlots() {
   googletag.cmd.push(function() {
     googletag.pubads().refresh();
   });
}

function clearAllSlots() {
  googletag.cmd.push(function() {
    googletag.pubads().clear();
  });
}

Note:

  • This example pertains to Google ads but similar functionality may apply to other ad platforms.
  • These methods can be invoked using lifecycle methods, hooks, or any suitable technique.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering the Art of Leveraging Conditionals in JavaScript's Find Function

I'm curious about the implementation of an if statement in the JavaScript find function. My objective is to add the class "filtered-out" to the elements in my cars array when their values do not match. cars.map(car => active_filters.find(x => ...

After the decimal point, there are two digits

My input field is disabled, where the result should be displayed as a product of "Quantity" and "Price" columns ("Quantity" * "Price" = "Total"). However, I am facing an issue where the result often displays more than 2 digits (for example: 3 * 2.93), desp ...

How to properly display date format in Node.js when using EJS templates with MySQL

When retrieving dates from the database, I am looking to break them down into two separate numbers. 7:00-8:00 //array[0]=7:00 and array[1]=8:00 9:00-9:30 14:30-15:00 Below is my code, but it is returning NaN NaN: <% time_slots.forEach((timeslot ...

The challenge of Angular form data binding

I'm encountering an issue with binding an input box to a controller in Angular. Despite following tutorials, the model never updates when I access the property or check the scope using AngularJS Batarang. Upon form submission, $scope.licenceKey remai ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

Display additional images with "Show More" view

I'm looking to create a view similar to the one shown in this image: https://i.stack.imgur.com/AZf61.png Within my FlatList, all the data is being populated including these thumbnails. These thumbnails are stored in an array of objects where I retri ...

When making an external API call, Next.JS automatically adds "localhost" to the URL

Recently, I encountered an issue with my Next.js app where an external API call was not working as expected. The problem arose when the API request had the Next.js app's address (localhost:3000) prepended to the actual URL, resulting in a 404 Not Foun ...

Simple steps to correct the npm installation of the React list filter

I encountered an issue while trying to install react-list-filter using npm (npm install react-list-filter). The error messages displayed in my console are as follows: npm ERR! code ETARGET npm ERR! notarget No matching version found for <a href="/cdn-c ...

Exploring the efficacy of unit testing on Express controllers

After days of working on this, I've hit a wall and finally decided to ask for assistance. Everything runs smoothly when the server is up and API calls are made. However, when attempting to unit test the controller, I encounter some issues. I'm ...

Could not find reference to Google (error occurred following ajax request)

I encountered an error message when attempting to use the Google Map after making an ajax call. ReferenceError: google is not defined The issue arises when I include the link "<script type="text/javascript" src="http://maps.google.com/maps/api/js?sen ...

Troubleshooting VueJS route naming issues

I am having an issue with named routes in my Vue app. Strangely, the same setup is working perfectly fine in another Vue project. When I click on a named router-link, the section just disappears. Upon inspecting the element in the browser, I noticed there ...

Having trouble with the base64 output in React image cropping?

I am having some difficulties cropping and uploading an image to the server. The API server requires the image in base64 format, but I am receiving it as a blob. Does anyone know of a workaround for this issue? Any help would be greatly appreciated! I&apos ...

Leveraging jQuery and Ajax for retrieving information from a JSON document

As a newcomer to JS, I have successfully set up a JSON file on my Express server. My code snippet looks like this: const data = require('./src/data.json') app.get('/search', function (req, res) { res.header("Content-Type",'app ...

Failure to implement Next.js 13 App Directory routing in a Spring Boot application

Recently, I came across a similar inquiry regarding integrating NextJS routing with a Spring Boot application without using any proxy I am currently working on setting up a Spring Boot application to serve a NextJS13 app Directory. The root page / (which ...

Collaborating on a single instance across several processes

I have a messaging bot in my project, where the connection is established using a class instance. class MessagingBot { public bot; constructor() { this.bot = new TelegramBot(); } } export default MessagingBot; In another file, I create an inst ...

An Undefined Session: Leveraging Connect-Redis with ExpressJS and Node.js

Upon waking up this morning, I was greeted with an error message from Nodejitsu: Warning: connection.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process. Determined to find ...

"Looking to log in with NextAuth's Google Login but can't find the Client Secret

I am attempting to create a login feature using Next Auth. All the necessary access data has been provided in a .env.local file. Below are the details: GOOGLE_CLIENT_ID=[this information should remain private].apps.googleusercontent.com GOOGLE_CLIENT_SECR ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

`an error occurs when trying to loop through an object and add a key``

I'm currently facing an issue with adding a key to an object through looping. Here is the code snippet: function checkResult(want, reference) { const keys = Object.keys(reference); for(let i=0; i<Object.keys(reference).length; i++){ console ...

Can values from a dgrid store be saved in a variable or displayed in the console?

Currently, I am utilizing the dgrid store to display a grid (dgrid 0.4) on my website. Below is the code snippet that I have implemented: require([ 'dojo/_base/declare', 'dojo/Deferred', 'dstore/RequestMemory', ...