@@ -5,22 +5,47 @@ require("../css/preview-frame.css");
5
5
interface PreviewFrameWindow extends PreviewFrame . Runner {
6
6
// This is exported by p5 when it's in global mode.
7
7
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 ;
8
13
}
9
14
10
15
let global = window as PreviewFrameWindow ;
11
16
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 ) {
14
18
let script = document . createElement ( 'script' ) ;
15
19
16
20
cb = cb || ( ( ) => { } ) ;
17
21
18
22
script . onload = cb ;
23
+ script . onerror = ( ) => {
24
+ console . log ( "Failed to load script: " + url ) ;
25
+ } ;
19
26
script . setAttribute ( 'src' , url ) ;
20
27
21
28
document . body . appendChild ( script ) ;
22
29
}
23
30
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
+
24
49
function LoopChecker ( sketch : string , funcName : string , maxRunTime : number ) {
25
50
let self = {
26
51
wasTriggered : false ,
@@ -92,9 +117,14 @@ function startSketch(sketch: string, p5version: string, maxRunTime: number,
92
117
errorCb ( message , line ) ;
93
118
} ) ;
94
119
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
+ } ) ;
98
128
}
99
129
100
130
global . startSketch = startSketch ;
0 commit comments