Aladin and Nicegui: how to run Javascript code automatically? #4086
-
QuestionHi, I am trying to use Aladin and nicegui together. When I add some JS code using "add_body_html" nothing happens. It is necessary to reload the page (which is not a smart solution) using a specific button in order to visualize the map. Can you explain me why? Is there a way to make this code work better? Thanks, Simo from nicegui import ui
def create_aladin_iframe():
return """
<div id="aladin-lite-div" style="width:800px;height:600px;"></div>
"""
def configure_aladin_iframe():
return """
<script type="text/javascript" src="https://aladin.cds.unistra.fr/AladinLite/api/v3/latest/aladin.js" charset="utf-8"></script>
<script type="text/javascript">
var aladin;
A.init.then(() => {
aladin = A.aladin('#aladin-lite-div', {target: 'M1'} );
});
</script>
"""
def reload():
ui.run_javascript('location.reload()')
with ui.row():
ui.html(create_aladin_iframe())
ui.add_body_html(configure_aladin_iframe())
ui.button('Reload page', on_click=reload) # <=== but WHY?! ...
ui.run() |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Uuuhh.. additional issue! ui.link('link.', 'https://google.com') it stops working at all (even with the button the map does not appear). |
Beta Was this translation helpful? Give feedback.
-
The issue is likely because the Aladin initialization script runs before the DOM element is fully loaded and available. When you reload the page, it works because all resources are cached and the timing happens to work out. Here's how to fix it by ensuring the script runs after the DOM is ready: ui.html('<div id="aladin" style="width:800px;height:600px"></div>')
ui.add_body_html("""
<script src="https://aladin.cds.unistra.fr/AladinLite/api/v3/latest/aladin.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
A.init.then(() => A.aladin('#aladin'));
});
</script>
""") |
Beta Was this translation helpful? Give feedback.
The issue is likely because the Aladin initialization script runs before the DOM element is fully loaded and available. When you reload the page, it works because all resources are cached and the timing happens to work out.
Here's how to fix it by ensuring the script runs after the DOM is ready: