1
- import { useRef , useLayoutEffect , useEffect } from "preact/hooks" ;
1
+ import { useRef , useLayoutEffect , useEffect , useState } from "preact/hooks" ;
2
2
import { cdnLibraryUrl } from "@/src/globals/globals" ;
3
3
4
4
interface CodeBundle {
@@ -86,6 +86,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
86
86
const p5ScriptTag = document . getElementById (
87
87
"p5ScriptTag" ,
88
88
) as HTMLScriptElement ;
89
+ const [ mounted , setMounted ] = useState ( false ) ;
89
90
90
91
// For performance, set the iframe to display:none when
91
92
// not visible on the page. This will stop the browser
@@ -101,11 +102,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
101
102
( entries ) => {
102
103
entries . forEach ( ( entry ) => {
103
104
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 ) ;
109
106
} ) ;
110
107
} ,
111
108
{ rootMargin : "20px" } ,
@@ -118,6 +115,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
118
115
useEffect ( ( ) => {
119
116
( async ( ) => {
120
117
if ( ! p5ScriptTag || ! iframeRef . current ) return ;
118
+ if ( ! mounted ) return ;
121
119
122
120
/*
123
121
* Uses postMessage to receive the text content of p5.min.js, to be included
@@ -148,7 +146,7 @@ export const CodeFrame = (props: CodeFrameProps) => {
148
146
return ;
149
147
}
150
148
} ) ( ) ;
151
- } , [ props . jsCode ] ) ;
149
+ } , [ props . jsCode , mounted ] ) ;
152
150
153
151
return (
154
152
< div
@@ -157,13 +155,13 @@ export const CodeFrame = (props: CodeFrameProps) => {
157
155
>
158
156
< iframe
159
157
ref = { iframeRef }
160
- srcDoc = { wrapInMarkup ( {
158
+ srcDoc = { mounted ? wrapInMarkup ( {
161
159
js : props . jsCode ,
162
160
css : props . cssCode ,
163
161
htmlBody : props . htmlBodyCode ,
164
162
base : props . base ,
165
163
scripts : props . scripts ,
166
- } ) }
164
+ } ) : undefined }
167
165
sandbox = "allow-scripts allow-popups allow-modals allow-forms allow-same-origin"
168
166
aria-label = "Code Preview"
169
167
title = "Code Preview"
0 commit comments