Search code examples
javascriptpythonhtmlbrython

How can I init brython without onload in <body>


It seems that initializing brython requires to be done like so:

<body onload="brython()">

I tried calling brython() in js in another <script> after having linked brython.js but it doesn't seem to get called.

When I finally call brython myself in the browser console, it calls brython, and even executes my python code.

To give a full example of what doesn't work, here is an example. I may be lacking some basic knowledge of how and when javascript is compiled and executed...

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/js/brython.js"></script>
</head>

<!-- <body onload="brython()"> -->
<body>

<script type="text/javascript">
console.log("calling brython() here");
brython();
console.log("I just called brython()");

</script>
<script type="text/python">
from browser import document, alert

def echo(*args):
    alert("Hello {} !".format(document["zone"].value))

document["test"].bind("click", echo)
print("what")

</script>
<p>Your name is : <input id="zone" autocomplete="off">
<button id="test">clic !</button>
</body>

</html>

Solution

  • The function brython() searches all the scripts with an attribute type="text/python" and executes the Python code inside.

    In your example, at the moment when you call the function, the Python script has not yet been loaded, so it's no surprise that it is not found and therefore executed. If you put the Javascript program after the Python script, it will work as you expect.