P5 starts drawing only after web page is done loading

I have written a preloader animation (supposed to be showed while page is loading in background) with p5 javascript library. But I observed that the animation did not start until the entire web page was loaded up, in my case a large image. This behaviour completely ruined the purpose of a preloader. I have also written an almost similar animation with javascript native ‘canvas’ and ‘setInterval’ features. To my surprise, this time, everything worked as expected. I suppose that p5.js calls ‘draw’ function after purser has finished loading html elements. Is there a way around to alter that?

Hi,

Are you loading your images with p5js? If so, are you using the preload() function?

The preload() function is blocking but if you want asynchronous loading, it says :

If asynchronous loading is preferred, the load methods can instead be called in setup() or anywhere else with the use of a callback parameter.

Otherwise, look like you can customize the loading message when waiting for a file to load :

By default the text “loading…” will be displayed. To make your own loading page, include an HTML element with id “p5_loading” in your page. More information here.

Maybe your issue is related to the order of the script tags inside your html or if you are using defer and async :

1 Like

Thanks for your reply.

I am not loading images with the preload() function.

I am using p5.js to animate the Preloader. So, if the script itself does not start drawing until the preload() function is done loading resources, then it actually makes no point. That’s why I did not use the preload() function.

Since I am not using defer or async, it should work theoretically.

A bunch of possible order of the scripts tags were tried. But unfortunately none of them worked.

I uploaded a basic version to codepen. Here is the link.

P. S. An image from wikimedia is included in the html to test the Preloader. And browser cache had to be deleted for testing purpose.

P.S.S I built the whole thing without the help of p5.js library in simple javascript (with canvas and setInterval() ). It is now working as expected.

1 Like

You can write your sketch using the “instance mode” which theoretically starts running even before the web page finishes loading:

If you prefer “global mode” you can use the new p5; trick I did on my sketch below:

window.mocha = 'Hack to block p5.js auto global instantiation.';
new p5; // Prematurely instantiates p5.js so its props are available now.
window._setupDone = undefined; // Blocks duplicate instantiation warn.
2 Likes