A loadXXX() call inside preload() doesn't delay draw()

Occasionally when my program loads images using loadImage the program fails to load them and then it gets stuck in the loading screen. When I look in the console it says img is undefined. Tracing this back, I find it happened when the program tried to draw a p5.Image in draw() that was loaded in preload(). Any ideas why this might happen or how to fix it would be heavily appreciated.

Hi @ubuntu-in-a-nutshell,

Can you be more precise about “fails to load them”? Because if for example the url of an image is wrong, it will stop the sketch before doing any draw() iteration.

Which loading failure are you talking about?



To get answers you need to post your sketch

1 Like

@ubuntu-in-a-nutshell, we need to know where and how you defined your variables. You can show us this along with other details that may be relevant by posting your code. Then we can test it, and experiment with possible solutions.

This only happens sometimes (and always after loading the resources for the first time). The behaviour of my program is mostly fine, sometimes it takes many reloads to get it to get stuck. Here’s my code.
Source script:

(https://buggem.github.io/GN9/src/main.js is the published version of the script)

Published game:

1 Like

I just got it to happen. Here are some images of my game. The background is supposed to be black, it’s a CSS rule I made, but the text is not supposed to be hidden.

Screen before highlighting text

Screen after highlighting text

All errors:

I think the resources probably weren’t loaded correctly, and now I will probably put a callback if it fails and in the callback reload the resource. I don’t want this to lead to InternalError: Too much recursion though.

I’ve quickly looked at your preload() callback from your “main.js” file.

Before anything else it’s completely unnecessary to use \/. Just go w/ a single slash character /.

Back to my finding, this statement below is wrong:

lines.menu = p.loadStrings(`${assets}\/menu.txt`).join('\n');

The reason why is b/c you invoke method Array::join() over an array which is still empty.

That is, function loadStrings() returns an empty array which will eventually be filled up w/ the text contents of a file.

Until the loading is fully complete we shouldn’t do anything w/ the returned array.

If you need to, create a success callback for it:

p.loadStrings(`${assets}/menu.txt`, arr => lines.menu = arr.join('\n'));

Or alternatively you can later make the final changes within setup() callback instead:

p.preload = function() {
  lines.menu = p.loadStrings(`${assets}/menu.txt`);

p.setup = function() {
  lines.menu = lines.menu.join('\n');