Optimize

Installing Optimize on Next.js

The key to installing Optimize on websites built with the Next.js framework is determining whether they use App Router or Pages Router. This page will focus on installing Optimize with the App Router.

Next.js with App Router

Locate the app/layout.js inside your project and paste the following scripts. Replace yourWebsiteName.js with the name of your site as listed on the ad tag page from the BuySellAds dashboard.

<head>
	<Script
		id="bsaOptimizeQueue"
		strategy="beforeInteractive"
	>
		{`window.optimize = window.optimize || { queue: [] };`}
	</Script>
</head>

<Script
	id="bsaOptimizeScript"
	strategy="afterInteractive"
	src={`https://cdn4.buysellads.net/pub/yourWebsiteName.js?${new Date() - new Date() % 600000}`}
/>

Create an Optimize component called OptimizeBody that you can load every page so it handles the ad refresh whenever the page URL updates.

'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';

const OptimizeBody = () => {
    const pathName = usePathname();

    useEffect(() => {
        window.optimize.queue.push(() => {
            window.optimize.pushAll();
        });
    }, [pathName]);

    return <div data-optimize="shadow-container"></div>;
};

export default OptimizeBody;

You can choose where to load the OptimizeBody component selectively. The simplest method is to include it just before the closing </body> tag in the app/layout.js file. If you’ve set up your project using the default configuration of Next.js, it typically appears like this.

// Rest of your layout code
import OptimizeBody from '@/components/OptimizeBody';

// The export of your layout code
export default function RootLayout({ children }) {
  return (
  <body>
  	{ /*Rest of body codes*/ }
  	<OptimizeBody/>
  </body>
  );
}

Next.js with Page Router

Create a new component called Optimize.js and copy the following code into it:

const init = (config = {}) => {
	window.optimize = window.optimize || { queue: [] }
	if (!config.src) {
		throw new Error(
			"The script 'src' property must be provided in the configuration.",
		)
	}
	window.optimize.src = config.src
}

const loadScript = () => {
const existingScript = document.getElementById('bsaOptimizeScriptID')
if (!existingScript) {
const bsa_optimize = document.createElement('script')
bsa_optimize.id = 'bsaOptimizeScriptID'
bsa_optimize.type = 'text/javascript'
bsa_optimize.async = true
bsa_optimize.src =
window.optimize.src + '?' + (new Date() - (new Date() % 600000))

    	bsa_optimize.onerror = () => {
    		console.error(`Failed to load script: ${window.optimize.src}`)
    	}

    	;(
    		document.getElementsByTagName('head')[0] ||
    		document.getElementsByTagName('body')[0]
    	).appendChild(bsa_optimize)
    }

}

export const pushAll = (config) => {
	init(config)
	loadScript()
	window.optimize.queue.push(() => {
		window.optimize.pushAll()
	})
}

Locate the top level component that handles the routing of your website. Usually, you can find them in _app.js file. You can identify them by referring to component that have this import line:

import { useRouter } from 'next/router'

Create the useEffect if you don't have one in the component and subscribe to the router events. We will be calling Optimize inside onRouteChangeComplete event. Here is the basic structure of most top level app component.

export default function App({ Component, pageProps }) {

	useEffect(() => {
		const onRouteChangeComplete = () => {
			Optimize.pushAll({src: 'https://cdn4.buysellads.net/pub/yourWebsite.js'});
		}
		
		onRouteChangeComplete()

		router.events.on('routeChangeComplete', onRouteChangeComplete)
		return () => {
			router.events.off('routeChangeComplete', onRouteChangeComplete)
		}
		
	}, [router.events])

	return (
		// The rest of layout components
	)
}