How to bulletproof JS script that relies on data fetch and html elements?

How to bulletproof JS script that relies on data fetch and html elements?

  

Hi,

We have a screen on our mobile app that uses nouislider script and the initial values for the slider are got from respective Entity. Most of the times the script and the whole page is working as expected but sometimes there is a js errors that may be relates to the fact that script is executed before DOM is ready. Currently we have script node that initialises slider on Entity after fetch event and probably it is possible that sometimes data is fetched before screen is ready. What is the best way to protect yourself from such errors? Have entity fetch onReady and then execute script - it triggers the warning?

Thank you.

Hi Mykola,

You can act on the DOM in the On Ready and On Render events of your screen and/or block. It is loaded by then.

Use this events to init your slider or set default values.

Hi Mykola,

If your UI doesn't make sense without initialising the nouislider script, I agree with João, just fetch (synchronously) the initialisation data you need on the OnReady event handler and initialise the script there.

If you can display your UI without initialising the script, I'd suggest a "slightly" more complex approach:

  • create local variables to hold initialisation data;
  • create local variable to flag OnReady has been executed (defaults to False)
  • on your OnReady event handler, check if initialisation data is there, if so initialise nouislider script, otherwise just skip initialisation for now. Before finishing, set the flag to True 
  • your OnAfterFetch check flag, if OnReady already executed it means it skipped initialisation so initialise nouislider now, otherwise, store initialisation data in local variables.

This way you to load asynchronously your script initialisation data, and you guarantee you only perform initialisation when you already have the full DOM.