Search code examples
pythonpyscript

Wait until pyscript packages are fully loaded and then modify the DOM


I want to wait until pyscript has fully loaded all packages and after that alter an element on the DOM.

I tried using window.addEventListener('load', create_proxy(func)) in pyscript. But to no avail, it does not execute the function. I also tried adding the event listener 'change' to the element that is being modified by pyscript. The element is used for inserting a table using the panel package. After the table is inserted I'd like to remove another element on the page.

Any help appreciated


Solution

  • The basic way is to use pyscript.write().

    <html>
        
        <head>
                
            <title>Pyscript - Test</title>
         
        <!-- Load required PyScript packages -->
            <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
            <script defer src="https://pyscript.net/alpha/pyscript.js"onerror=scriptLoadFailure('pyscr ipt.js')></script>
    
    <py-env>
    - pandas
    </py-env>
    
        </head>
        
    <!-- ------------------------------------------------------------------- -->
        <body>
            
    <py-script>
    import pandas as pd
    def do_it():
        df = pd.DataFrame([[12, 14, 10, 11, 1], [22, 24, 20, 21, 0]])
        pyscript.write('output', df)
        pyscript.write('msg', 'That should be it')
    do_it()
    </py-script>
            <header id="header_top">Pyscript - Test</header>
            <div id="main1">
                <div id="output">
                    Testing div with id="output" 
                </div>
                <div id="msg"></div>
            </div>
        </body>
    <!-- ------------------------------------------------------------------- -->
    </html>
    

    While loading the content of the paage is
    Pyscript - Test
    Testing div with id="output"

    After loading has finished there is a pandas df in the output div and additional text in a separate div with id="msg"
    "That should be it" Regards...
    enter image description here