1- import { useRef , useLayoutEffect , useEffect } from "preact/hooks" ;
1+ import { useRef , useLayoutEffect , useEffect , useState } from "preact/hooks" ;
22import { cdnLibraryUrl } from "@/src/globals/globals" ;
33
44interface CodeBundle {
@@ -86,6 +86,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
8686 const p5ScriptTag = document . getElementById (
8787 "p5ScriptTag" ,
8888 ) as HTMLScriptElement ;
89+ const [ mounted , setMounted ] = useState ( false ) ;
8990
9091 // For performance, set the iframe to display:none when
9192 // not visible on the page. This will stop the browser
@@ -101,11 +102,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
101102 ( entries ) => {
102103 entries . forEach ( ( entry ) => {
103104 if ( ! iframeRef . current ) return ;
104- if ( entry . isIntersecting ) {
105- iframeRef . current . style . removeProperty ( "display" ) ;
106- } else {
107- iframeRef . current . style . display = "none" ;
108- }
105+ setMounted ( entry . isIntersecting ) ;
109106 } ) ;
110107 } ,
111108 { rootMargin : "20px" } ,
@@ -118,6 +115,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
118115 useEffect ( ( ) => {
119116 ( async ( ) => {
120117 if ( ! p5ScriptTag || ! iframeRef . current ) return ;
118+ if ( ! mounted ) return ;
121119
122120 /*
123121 * Uses postMessage to receive the text content of p5.min.js, to be included
@@ -148,7 +146,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
148146 return ;
149147 }
150148 } ) ( ) ;
151- } , [ props . jsCode ] ) ;
149+ } , [ props . jsCode , mounted ] ) ;
152150
153151 return (
154152 < div
@@ -157,13 +155,13 @@ export const CodeFrame = (props: CodeFrameProps) => {
157155 >
158156 < iframe
159157 ref = { iframeRef }
160- srcDoc = { wrapInMarkup ( {
158+ srcDoc = { mounted ? wrapInMarkup ( {
161159 js : props . jsCode ,
162160 css : props . cssCode ,
163161 htmlBody : props . htmlBodyCode ,
164162 base : props . base ,
165163 scripts : props . scripts ,
166- } ) }
164+ } ) : undefined }
167165 sandbox = "allow-scripts allow-popups allow-modals allow-forms allow-same-origin"
168166 aria-label = "Code Preview"
169167 title = "Code Preview"
0 commit comments