We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I've got a complex modern frontend web application which goes through a series of transformations to the DOM before reaching the "page" where I want to use p5.js.
However, p5.js automatically calls setup() and starts running as soon as the DOM is loaded. Is there a way to tell p5 not to run my sketch on DOM load and instead trigger it running through a specific API call at the right point in the lifecycle of my wider application?
Thanks!
Answers
https://GitHub.com/processing/p5.js/wiki/Instantiation-Cases
Can't you just dynamically inject the p5js script only when you need it?
You can setup your sketch in instance mode and call new p5() whenever you're ready to run. https://github.com/processing/p5.js/wiki/p5.js-overview#instantiation--namespace
Note there's also a remove method: http://p5js.org/reference/#p5/remove
This is the technique we're using for hello.p5js.org.
This should include a mechanism for dependency management: use it. Don't just load p5 with everything else at the beginning and have it sitting around hogging memory unnecessarily. Even with plain JS it's relatively straightforward to dynamically load script resources...
Also definitely use instance mode in this context!
Thanks, Lauren! That's exactly what I was looking for.
One small additional comment: it might be nice to provide a callback that runs after the sketch has finished rendering. I know I could implement this myself by calling a function from inside the sketch, but that would require making my sketch dependent on stuff going on outside of it that it shouldn't know about.
Instead, at the moment, I handle it using a MutationObserver:
https://gist.github.com/atduskgreg/734dcd32e80283b83ca5cb82d69030bd
But it would be useful (and more accessible) if the constructor just took a callback.