Unable to reload script when navigated to another page
Unanswered
Keyhole wasp posted this in #help-forum
Keyhole waspOP
I am trying to reload the ad script on each page, but it only works when I refresh the page. So, I see the ad showing only when the page is refreshed. Have a look at the code:
In the component where I want to show ad:
I'm importing the LoadAd component in the app's root directory (page.js). I have tried using next's usePathname to force reload, but it did not work.
If you want to see the issue live, what is happening here is the live version: (https://calculatecgpa.com)
Go to the fact of the day page and come back home. You will see the ad below is not showing.
"use client"
import { usePathname } from "next/navigation";
import { useEffect } from "react";
export function LoadAd() {
useEffect(() => {
const pathname = usePathname();
const script = document.createElement("script");
script.src =
"//pl22500737.profitablegatecpm.com/1c8566c67a4bf36055e7f55caabeabb0/invoke.js";
script.async = true;
document.body.appendChild(script);
return () => {
script.remove();
};
}, [pathname]);
return (
null
);
}In the component where I want to show ad:
const Home = () => {
<div
className="mx-auto max-[350px]:hidden w-[300px] h-72 max-h-72"
id="container-1c8566c67a4bf36055e7f55caabeabb0"></div>
);
};
export default Home;I'm importing the LoadAd component in the app's root directory (page.js). I have tried using next's usePathname to force reload, but it did not work.
If you want to see the issue live, what is happening here is the live version: (https://calculatecgpa.com)
Go to the fact of the day page and come back home. You will see the ad below is not showing.
2 Replies
Asian black bear
try
document.body.removeChild(script) instead script.remove@Asian black bear try `document.body.removeChild(script)` instead `script.remove`
Keyhole waspOP
Not working. I have even tried document.getElementById("ad").remove() but no success. I just checked the elements in developer tools and found out that the script tag is not removing from the DOM. Do you know why it is not being removed?