Announcing Dash Bio 1.0.0 🎉 : a one-stop-shop for bioinformatics and drug development visualizations.

Window.onload is not working with Dash canvas

What I am trying to do is to place one Rive animation inside a HTML Canvas with id Canvas. Then from javascript side I am trying to load an animation inside the canvas. Sometimes it works and sometimes it does not work.

app.py

import dash
from dash import html, dcc
import dash_bootstrap_components as dbc

# adding external script and stylesheets
external_scripts = ['https://unpkg.com/rive-js@0.7.16/dist/rive.min.js']
external_stylesheets = [dbc.themes.CYBORG]


app = dash.Dash(__name__, external_stylesheets=external_stylesheets, external_scripts=external_scripts)
server = app.server

app.layout = html.Div([
    html.Canvas(id='canvas', style={'width': '100%'}),
])


if __name__ == '__main__':
    app.run_server(debug=True, host='0.0.0.0')

script.js

window.addEventListener('load', function () {
let cc = document.getElementById('canvas');
console.log(cc);
  new rive.Rive({
        src: './assets/website_bg.riv',
        canvas: document.getElementById('canvas'),
        layout: new rive.Layout({fit: 'cover'}),
        autoplay: true,
    });
});

Capture

Upon investigation, I found that the canvas or the variable cc is null sometimes. I am not good at React, why the canvas is not loaded yet although I am using window.onload callback? Any workaround this?

For the time being I have solved this with this hack (thanks to dash community)

function addAnimationToCanvas() {
    let canvas = document.getElementById('canvas');
    if(canvas){
        new rive.Rive({
                src: './assets/website_bg.riv',
                canvas: document.getElementById('canvas'),
                layout: new rive.Layout({fit: 'cover'}),
                autoplay: true,
            });
        clearInterval(refreshID);
        }
    }

let refreshID = setInterval(addAnimationToCanvas, 250);

But I am looking for more elegant solution.