How do the p5.js preload functions work?

I’m just interested in how it was implemented that functions like loadFont() or loadImage() can be called with a callback or in the preload function. How does p5.js know, when preload is done and when it is save to call setup. And how are the loaded resources placed into the variables? I’ve read somewhere online that it’s done with some kind of counter, but how does p5.js know how many functions you called inside the preload-function and what the counter is supposed to be set to?

P5.js is open-source, so you can see exactly how the preload() function works by looking at the code here.

Do a ctrl+f for “preload” in that file to read through the functions related to preloading.

1 Like

I actually did look at the source code beforehand, but didn’t understand it…

What part of the code do you have questions about? What don’t you understand?

While asking your question, note that you can click on line numbers next to the github source code to get a more specific url, then cut and paste that URL into the forum, like this (line 600):

2 Likes

I am sorry. may i ask where is decrement part?
I only see_decrementPreload() declaration but there is no line used this fucntion

I think you are asking where in code is _decrementPreload called? You can find all references using github search:

Could someone tell me if this is the correct way to use registerPreloadMethod?

https://editor.p5js.org/ChrisOrban/sketches/nlsT8N4mg

The first time you press play there is a 1-2 second delay before the video starts. I really need the video to start right as the sketch starts to run. If you press stop and then play it will sync up but I need it to do this the first time. That’s why the preload function exists right?