Can PyScript lazy loading defer startup until first interaction?
0 reputation · 21 Mar 2024, 00:23 UTC
0 reputation · 21 Mar 2024, 00:23 UTC
For a PyScript page with occasional user interactions, the goal is to decide whether lazy module loading and WebWorker execution can defer enough startup work to justify the added configuration. This assumes a current PyScript release; the exact version matters because default extensions and loading behavior may vary.
The unresolved point is what “lazy” actually defers. Module imports may be postponed while interpreter or WebAssembly initialization still occurs during page load. Browser-specific WebAssembly performance, retained memory after a single Python call, and repeat-visit caching can also change the cost comparison. The evaluation should compare transferred bytes, main-thread blocking, time to first Python response, and post-use heap size under otherwise identical pages.
Does PyScript lazy loading defer interpreter startup as well as module imports, or only the imports? Which measurements should determine whether worker execution and extension trimming are worthwhile for a low-traffic page?
35775 reputation · 21 Mar 2024, 08:56 UTC
PyScript lazy loading defers module imports, not interpreter startup. The WebAssembly runtime (pyodide.asm.wasm) loads and initializes during page load whenever a <py-script> element exists or pyodide.load() is called, regardless of lazy import statements.
In PyScript 0.5+, lazy imports via import statements postpone the download and compilation of specific Python modules, but the core interpreter must still be instantiated first. This means:
For a low-traffic page, compare these measurements:
Run these checks to confirm actual behavior on your page:
# 1. Check network waterfall
Open DevTools > Network, reload page
Verify pyodide.asm.wasm downloads before any .py files
# 2. Log interpreter initialization
console.log('Before load');
await pyodide.load();
console.log('After load');
# 3. Measure main-thread blocking
const start = performance.now();
await pyodide.load();
console.log('Blocking:', performance.now() - start, 'ms');
If your page has "occasional user interactions," WebWorker execution may provide better perceived performance than lazy imports alone, since it moves the heavy WASM initialization off the critical path. However, you'll need to measure the actual bytes transferred and blocking time for your specific use case—browser caching and network conditions significantly affect the trade-off.
One missing detail: Which PyScript version are you targeting? Behavior differs between 0.5.x and later releases.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.