Skip to content

Commit 9e7a745

Browse files
authored
Merge pull request #63 from toolness/preview-frame-addon-plumbing
Add foundational support for loading p5 addons in preview-frame.ts.
2 parents b451c1c + 1e23d92 commit 9e7a745

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

lib/preview-frame.ts

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,47 @@ require("../css/preview-frame.css");
55
interface PreviewFrameWindow extends PreviewFrame.Runner {
66
// This is exported by p5 when it's in global mode.
77
noLoop: () => void;
8+
9+
// This is the p5 constructor. An undocumented feature is that
10+
// even the first argument is actually *optional*; if omitted,
11+
// p5 will initialize itself in global mode.
12+
p5: (sketch?: Function, node?: HTMLElement, sync?: boolean) => void;
813
}
914

1015
let global = window as PreviewFrameWindow;
1116

12-
function loadP5(version: string, cb?: () => void) {
13-
let url = '//cdnjs.cloudflare.com/ajax/libs/p5.js/' + version + '/p5.js';
17+
function loadScript(url, cb?: () => void) {
1418
let script = document.createElement('script');
1519

1620
cb = cb || (() => {});
1721

1822
script.onload = cb;
23+
script.onerror = () => {
24+
console.log("Failed to load script: " + url);
25+
};
1926
script.setAttribute('src', url);
2027

2128
document.body.appendChild(script);
2229
}
2330

31+
function loadScripts(urls: string[], cb?: () => void) {
32+
cb = cb || (() => {});
33+
34+
let i = 0;
35+
let loadNextScript = () => {
36+
if (i === urls.length) {
37+
return cb();
38+
}
39+
loadScript(urls[i++], loadNextScript);
40+
};
41+
42+
loadNextScript();
43+
}
44+
45+
function p5url(version: string) {
46+
return `//cdnjs.cloudflare.com/ajax/libs/p5.js/${version}/p5.js`;
47+
}
48+
2449
function LoopChecker(sketch: string, funcName: string, maxRunTime: number) {
2550
let self = {
2651
wasTriggered: false,
@@ -92,9 +117,14 @@ function startSketch(sketch: string, p5version: string, maxRunTime: number,
92117
errorCb(message, line);
93118
});
94119

95-
document.body.appendChild(sketchScript);
96-
97-
loadP5(p5version);
120+
loadScripts([
121+
p5url(p5version),
122+
], () => {
123+
document.body.appendChild(sketchScript);
124+
if (document.readyState === 'complete') {
125+
new global.p5();
126+
}
127+
});
98128
}
99129

100130
global.startSketch = startSketch;

0 commit comments

Comments
 (0)