I am developing a React component in Next.js that uses an iframe for ad rendering. The current implementation directly sets the src
attribute of the iframe and attaches a load
event listener via useEffect
. Upon deployment to production, I observed that the handleIframeLoad
method is not getting executed for high number of requests. Below is the relevant code snippet:
...
useEffect(() => {
const iframe = iframeRef.current;
...
if (iframe) {
iframe.addEventListener("load", handleIframeLoad);
}
...
return () => {
if(iframe) {
iframe.removeEventListener("load", handleIframeLoad);
}
}
});
...
return (
<iframe
ref={iframeRef}
src={props.src}
style={{
border: "none"
}}
/>)
Since the handleIframeLoad
method is not getting executed, it suggests that the “load” event from browser is not getting captured. It seems like the load event is getting triggered before event listener is getting attached to the iframe.
In local testing, I found that adding a check for iframe ready
state may work but I am not sure if it covers all cases in production:
if (iframe) {
if (iframe.contentDocument?.readyState === "complete") {
handleIframeLoad();
} else {
iframe.addEventListener("load", handleIframeLoad);
}
}
Also adding the onLoad
attribute in iframe
directly may also work but it will limit the flexibility of removing the event listener dynamically (needed for a specific use case):
return (
<iframe
ref={iframeRef}
src={props.src}
onLoad={handleIframeLoad}
style={{
border: "none"
}}
/>)
Basically, I want to know what is the best way to make sure iframe “load” event gets captured every time.
ijamortira is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.