How to put js after DashRenderer() in Dash?

The document.querySelector(’#id’) is null in js. I’m guessing that the error occurred because I imported js files that were executed before DashRenderer().

// The scripts oreder in HTML
// <script src="/assets/js/nav-menu.js?m=1623147446.3624363"></script>
// <script src="/_dash-component-suites/dash_renderer/dash_renderer.v1_9_1m1622237833.dev.js"></script>
            // <script id="_dash-renderer" type="application/javascript">var renderer = new DashRenderer();</script>
var renderer = new DashRenderer();

So my question is how can I put the js (in assets) after the render event to make sure my statement is no longer null?

You can use the Import component of the dash_defer_js_import library.

Thanks for your help! But the dash_defer_js_import not works very well…

I have used it a few times myself without encountering any issues. If you intend to get help on how to proceed, you should be more specific about your issue than “not works very well”.

Thank you very much. I would like to know if I am using this correctly.

# import dash_defer_js_import as defer_load
app.layout = html.Div([
    defer_load.Import(src="./assets/js/nav-menu.js"),
    NavBar,
    Upload,
    html.Div(id='output-image-upload'),
])

And do I need to put the js file in a separate folder instead of the assets folder?

It seems that when using dash_defer_js_import, it loads the js in the assets folder 2 times. The error occurs when I use the let declaration.

1 Like

It is probably loaded before (all files in the assets folder are) and after (via the import component) react loads. If possible, the easiest would be just to load the js code via an external url. Alternatively, you can use the flask server to serve the js code.

EDIT: You could also try the ignore option,

Thank you so much for your help, I added a filter to assets_ignore so that it doesn’t load 2 times.