How to load data during layout

I have an app that needs to query data from an external source, which takes about 10 seconds. In an ideal world, my app would load (that is, the layout would be drawn first), and then the data would load in the background so that it would be readily available once the user started interacting with the app.

Because of the time delay for fetching the data, I do not want to trigger this fetching routine with every input change. My current solution is to load this data in the layout, which is defined as a function, so that it is loaded on every page refresh. However, what that ends up doing is preventing the layout from being drawn, so I’m left looking at a blank page for several seconds until the data has been fetched, and the layout function is returned.

Is there a way around this so that the layout can be drawn first, and then the data retrieved? I would be fine with putting the fetching routine in a separate callback, but there are no input elements that would trigger it, and callbacks require at least one input.

Hello @shwiftyRick,

You could have the function to pull the data be triggered from the dcc.Location in a callback.

This would load the data independently and should cause it to pull each time there is a location change, or the page is refreshed should also trigger it.

Thank you @jinnyzor this works for me! However, I am forced to set prevent_initial_call=False in order for this to actually trigger the callback. I believe that this also means that this callback will be triggered not just on page load, but on parent app load (that is, when it is dockerized or otherwise initially spun up), is that correct?

If possible, I’d like to not introduce that overhead to the runtime on parent app load, but rather have this execute ONLY when the child app is viewed.

I could be wrong about this, and my understanding of how Dash callbacks are executed. Please correct me if so.

I don’t think that this would cause loading on the app spin up.

But not sure if that’s what you mean exactly.

Yes, that was what I was asking about. I thought that all callbacks, when not explicitly defined with prevent_initial_callback=True would get triggered on app spin up.

I dont think so, they will get triggered upon the page loading, which is actually something that I believe you want to happen.

The app process spin up only verifies the layout.

Perfect, then this is exactly what I was looking for! Thanks again!!

1 Like

Be sure to give it a test. :smiley: