How to catch the event that all py-script tags were executed?

Is there a way to know that all py-script tags were executed and all nodes were rendered from within javascript?

2 Likes

I am not sure if there is an event that Pyodide sends. For my code, I create a global variable in JavaScript and then set that variable when my Python code finishes. Then in JavaScript, I have a while/sleep loop that waits for the flag to be set. Your Python code could also send an event that JavaScript can catch and then execute that code.

If you are using multiple <py-script> tags, my method would require multiple flags or increments to one flag.

There must be a better way, but here is how I do it:

JavaScript:

<script>
let py_inited = false;
</script>

Python:

import js
# do stuff
js.py_inited = True
1 Like

Thanks for your answering!

It was found PyScript does not have any APIs to tell the script was done. As you thought, to know the script was executed, we need to add a script to do it.

The list below is the things I knew by my experiment.

  • pyscript tags are successively executed
  • pyscript output the data to the node after that all pyscript tags were done
  • but pyscript.write() render synchronously
  • lastly pyscript are added event listeners to the created elements

To know the all scripts were executed and the all nodes were rendered, write a script like below

./py-inited.js

window.addEventListener("DOMContentLoaded", () => {
  const pyCollectedOutput = document.createElement("div");
  pyCollectedOutput.setAttribute("id", "py-collected");
  document.body.appendChild(pyCollectedOutput);

  const pyInitedPyScript = document.createElement("py-script");
  pyInitedPyScript.setAttribute("id", "py-inited");
  pyInitedPyScript.setAttribute("src", "./py-inited.py");
  pyInitedPyScript.setAttribute("output", "py-collected");
  document.body.appendChild(pyInitedPyScript);

  window.pyInitedEvent = new Event("py-inited");
  document.addEventListener("py-inited", () => {
    document.body.removeChild(pyInitedPyScript);
    console.log("pyscript tags were initialized!");
  });

  const observer = new MutationObserver(() => {
    document.body.removeChild(pyCollectedOutput);
    console.log("pyscript tags were collected!");
  });
  observer.observe(pyCollectedOutput, {
    childList: true,
  });
});

./py-inited.py

import js

js.document.dispatchEvent(js.pyInitedEvent)
1 Like

Your post is very interesting. I must research a few new items that I just learned from your post. Thank you for sharing,