Lifecycle Guarantees of preload()
In p5.js, preload() is designed to ensure that all assets loaded via built-in functions (such as loadImage(), loadSound(), and loadFont()) are fully resolved before setup() is invoked. The framework internally tracks these asynchronous requests and defers the execution of the rest of the sketch lifecycle until all pending p5.js load calls have completed.
Consistency Across Deployment Targets
The sequencing of preload() $\rightarrow$ setup() is consistent across deployment targets (Web Editor, npm bundles, or local servers) because it is managed by the p5.js library logic rather than the hosting environment. However, the reliability of the assets arriving depends on the browser's network layer and the server's configuration.
Edge Cases and Failure Modes
While the sequence is guaranteed, setup() may proceed with partially loaded or missing assets in the following scenarios:
- Native Async Calls: If you use native
fetch() or XMLHttpRequest inside preload() without using p5.js wrappers, the framework cannot track these requests. setup() will execute regardless of whether these native calls have finished.
- CORS and CSP Restrictions: Content Security Policies (CSP) or missing Cross-Origin Resource Sharing (CORS) headers on the asset server can block requests. Depending on the version and environment, a blocked request may either hang the sketch indefinitely or trigger an error that allows
setup() to proceed with a null or broken asset.
- Network Timeouts: Extreme latency or timeouts may result in assets failing to load, leading to runtime errors in
setup() or draw() when the code attempts to access the missing resource.
Verification Steps
To verify asset readiness in your specific deployment target, use the following scoped approach:
- Execution Order Check: Place a
console.log('Loading...') in preload() and a console.log('Ready!') in setup(). The "Ready!" message should never appear before the network tab shows the assets have finished downloading.
- Network Inspection: Open Browser Developer Tools $\rightarrow$ Network Tab. Ensure all assets return a
200 OK status before the canvas initializes.
- CORS Validation: If assets fail only in production, check the
Access-Control-Allow-Origin header on the remote server.
Diagnostic Detail Required: Are you using any non-p5.js loading libraries (e.g., Axios) or native JavaScript async/await patterns inside your preload() function?