how can I append 3rd party scripts only on a specific page?
Unanswered
Yaman posted this in #help-forum
YamanOP
I want to add a script only in the checkout page I do not want it to be global in my application so I do not want to it in:
so I tried to use:
but I get the following warning:
when I try to use next/script:
I get this warning:
how can I add the script only in the required page?
is there any workaround?
also how can I wait for the script to finish loading before rendering anything?
because the script is required to be fully loaded before I render anything related to the payment
_document.tsxso I tried to use:
<Head>
<script src="https://cdn.checkout.com/js/framesv2.min.js" async />
</Head>but I get the following warning:
Do not add <script> tags using next/head (see <script> tag with src="https://cdn.checkout.com/js/framesv2.min.js"). Use next/script instead.when I try to use next/script:
<Script
src="https://cdn.checkout.com/js/framesv2.min.js"
strategy="beforeInteractive"
/>I get this warning:
`next/script`'s `beforeInteractive` strategy should not be used outside of `pages/_document.js`.how can I add the script only in the required page?
is there any workaround?
also how can I wait for the script to finish loading before rendering anything?
because the script is required to be fully loaded before I render anything related to the payment
2 Replies
YamanOP
I make this hook please can anyone review it?
usage:
import { useEffect } from "react";
const useExternalScripts = (
src: string,
attributes: Record<string, string> = {},
onload: (() => void) | null = null,
appendToHead: boolean = false
) => {
useEffect(() => {
const tempScript = document.createElement("script");
tempScript.setAttribute("src", src);
Object.keys(attributes).forEach((att) => {
tempScript.setAttribute(att, attributes[att]);
});
tempScript.onload = () => {
if (onload) {
onload();
}
};
if (appendToHead) {
document.head.appendChild(tempScript);
} else {
document.body.appendChild(tempScript);
}
// Clean up the script when the component unmounts
return () => {
if (tempScript) {
tempScript.remove();
}
};
}, [src, attributes, onload, appendToHead]);
};
export default useExternalScripts;usage:
import { useState } from "react";
import { CardFrame } from "frames-react";
import useExternalScripts from "@/hooks/useExternalScripts";
const CardCheckout = () => {
const [loaded, setLoaded] = useState<boolean>(false);
useExternalScripts(
"https://cdn.checkout.com/js/framesv2.min.js",
{},
() => {
setLoaded(true);
},
true
);
if (!loaded) {
return <div>Loading...</div>;
}
return (
<div className="overflow-hidden">
<CardFrame />
</div>
);
};
export default CardCheckout;Asian black bear
The only way to make the script go away is a hard reload. Removing the script tag does nothing. Hope that helps