Skip to content

Commit 9513801

Browse files
committed
Merge pull request #812 from processing/feat/perf
Fully unmount sketches that go out of frame
1 parent dd79321 commit 9513801

File tree

1 file changed

+7
-9
lines changed

1 file changed

+7
-9
lines changed

src/components/CodeEmbed/frame.tsx

+7-9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useRef, useLayoutEffect, useEffect } from "preact/hooks";
1+
import { useRef, useLayoutEffect, useEffect, useState } from "preact/hooks";
22
import { cdnLibraryUrl } from "@/src/globals/globals";
33

44
interface 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

Comments
 (0)