It looks something like this:
Along with this I have div tags that I place on the web page, for example:
<div id="ad-tag-6098" ></div> <div id="ad-tag-6099" ></div> <div id="ad-tag-6076" ></div>
This works fine on a normal load /reload of a page.
What is the correct way to reload the ad.js so that the div tags (ad slots) display the ad correctly, and also refresh correctly even when we navigate through the nextjs router? Can you please help?
The desired behaviour is as follows:
- when the ad component is rendered, it defines the ad slot and displays it,
- when route is changed, all defined slots are removed from the memory,
- after going to a different page, ad components on that page define new slots and display them.
You might know but I wanted to remind you that there are listeners for route changes in NextJS
router.events.on('routeChangeComplete', handleRouteChange) router.events.off('routeChangeComplete', handleRouteChange)
you can reload the script when the route changes with the help of these events. you can fetch the script and append it at the end of the body script for every route change. so the memory of the adjs will be restarted
I hope this router.events helps, waiting for your feedback.
If you are the one adding all the ad divs, you can add an data attribute to select those divs later.
For example, Lets say you have 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 using routeChangeStart event of router.events, you can select the divs with data-ad attribute and remove the filled content of them from DOM before routeChangeComplete event and when script is reloaded, it should not throw an error.
const adDivs = document.querySelectorAll('[data-ad="true"]'); // you can get these divs and remove the child of them before routeChangeComplete cycle
What do you think about this updated part of my answer, let me know your thoughts.