How to make my page load faster?

I’m sorry if my question has already been posted here before.

What I’m trying to do:
My dashboard page took almost 30 seconds to open. Inside, a couple of graphs took the data from the server module. I’m using daily data from 2 March 2020 to July 2022, with 7 columns including Date
What I’ve tried and what’s not working:

Code Sample:

# Client Dashboard Code
class dashboard(dashboardTemplate):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.ass()
    # Any code you write here will run when the form opens.
    
    fig1 = anvil.server.call('create_plots')
    self.plot_1.figure=fig1
    fig2 = anvil.server.call('create_plots2')
    self.plot_2.figure=fig2
    fig3 = anvil.server.call('create_plots3')
    self.plot_3.figure=fig3
    fig4 = anvil.server.call('create_plots4')
    self.plot_4.figure=fig4
#     fig5 = anvil.server.call('create_plots5')
#     self.plot_5.figure=fig5
#     mxpos= anvil.server.call('info_dat')
#     self.highest_pos_lbl.text =mxpos
#     fig4 = anvil.server.call('create_plots4')
#     self.plot_4.figure=fig4
################### Dashboard Info ############
  def ass(self):
    # self.plot_1.data = go.Bar(y=[100,400,200,300,500])
    dfa = anvil.server.call('get_dash')
    conf = sorted(dfa, key=lambda x: x['tanggal'], reverse=True)[0]
    conf1 = sorted(dfa, key=lambda x: x['tanggal'], reverse=True)[1]
    self.confirmcase_lbl.text ="{:,d}".format(conf['confirm'])
    self.activecase_lbl.text ="{:,d}".format(conf['active'])
    self.recovercase_lbl.text ="{:,d}".format(conf['recovered'])
    self.deathcase_lbl.text ="{:,d}".format(conf['Death'])
    self.tanggal_lbl.text =conf['tanggal']
#   Menghitung kenaikan kasus
    diffs_conf =(conf['confirm'],lambda x: x[0] - x[1])
    self.conf_selisih_lbl.text ="{:,d} Cases".format(conf['confirm']-conf1['confirm'])
    self.recover_selisih_lbl.text ="{:,d} Case".format(conf['recovered']-conf1['recovered'])
    self.death_selisih_lbl.text ="{:,d} Case".format(conf['Death']-conf1['Death'])
    self.activecase_selisih_lbl.text ="{:,d} Case".format(conf['active']-conf1['active'])
########################################    

  
###################LAST PANEL##########################
#     media_obj = anvil.server.call('make_plot')
#     self.image_1.source = media_obj
#     self.download_link.url = media_obj

  def plot_1_click(self, points, **event_args):
    """This method is called when a data point is clicked."""
    pass

  def plot_2_click(self, points, **event_args):
    """This method is called when a data point is clicked."""
    pass

  def plot_3_click(self, points, **event_args):
    """This method is called when a data point is clicked."""
    pass


  def plot_4_click(self, points, **event_args):
    """This method is called when a data point is clicked."""
    pass

# Server Module Code
######################### Plotting Dashboard#########################
def csv_to_df(f):
  d=app_tables.data.get(file_name=f)['file']
  dfa=pd.read_csv(io.BytesIO(d.get_bytes()),sep=';')
  return dfa

@anvil.server.callable
def prepare_cov_data():
  covup_df = csv_to_df('covid19')
  covup_df['Date']= pd.to_datetime(covup_df['Date'],format='%d/%m/%Y')
  return covup_df

########INDONESIA COVID-19#############
@anvil.server.callable
def create_plots():
  covup_df= prepare_cov_data()
  fig1 =px.line(covup_df,x='Date',y=covup_df["Positif_kumulatif"])
  fig1.update_xaxes(title_text='Date')
  fig1.update_yaxes(title_text='Cumulative Cases')  
  fig1.update_layout(
    template="plotly_white",
    xaxis_rangeslider_visible=True
    
  )
  fig1.show()
  return fig1
@anvil.server.callable
def create_plots2():
  covup_df= prepare_cov_data()
  fig2 = px.line(covup_df, x = "Date", y = "Sembuh_kumulatif")
  fig2.update_xaxes(title_text='Date')
  fig2.update_yaxes(title_text='Cumulative Cases')
  fig2.update_layout(
    template="plotly_white",
    xaxis_rangeslider_visible=True
  )
  fig2.show()
  return fig2
@anvil.server.callable
def create_plots3():
  covup_df= prepare_cov_data()
  fig3 =px.line(covup_df, x = "Date", y = "Meninggal_Dunia_kumulatif")
  fig3.update_xaxes(title_text='Date')
  fig3.update_yaxes(title_text='Cumulative Cases')
  fig3.update_layout(
    template="plotly_white",
    xaxis_rangeslider_visible=True

  )
  fig3.show()
  return fig3
@anvil.server.callable
def create_plots4():
  covup_df= prepare_cov_data()
  fig4 = go.Figure()
  fig4.add_trace(go.Scatter(x=covup_df['Date'], y=covup_df['New_Positive'],
                    mode='lines',
                    name='Active Case'))
  fig4.add_trace(go.Scatter(x=covup_df['Date'], y=covup_df['Sembuh'],
                    mode='lines',
                    name='Recover'))
  fig4.add_trace(go.Scatter(x=covup_df['Date'], y=covup_df['Meninggal_Dunia'],
                    mode='lines', name='Death'))
  fig4.update_xaxes(title_text='Date')
  fig4.update_yaxes(title_text='Daily Cases')
  
  fig4.update_layout(
    template="plotly_white",
    xaxis_rangeslider_visible=True
  )
  fig4.show()
  return fig4
#################################################################################
**Clone link:**

*share a copy of your app*
https://indonesia-covid19-lstmprediction.anvil.app

Thankyou
1 Like

Server calls are relatively slow. Meaning, if you do many anvil.server.call('your_server_module_code') in order to load a Form, it can greatly decrease the load times of the page.

In your code, you make 5 calls to the server, in order to load the dashboard.

This could be optimized, by having a single server call, which gets retrieves the data on the server side, and returns the data to the client once.

Something like:

Server code: (Not tested code)

@anvil.server.callable
def get_plots():
  result = {
    "plot1": create_plots(),
    "plot2": create_plots2(),
    "plot3": create_plots3(),
    "plot4": create_plots4(),
  }
  return result

Client code: (Not tested code)

# Client Dashboard Code
class dashboard(dashboardTemplate):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.ass()
    # Any code you write here will run when the form opens.
    
    plots = anvil.server.call('get_plots')
    self.plot_1.figure=plots['plot1']
    self.plot_2.figure=plots['plot2']
    self.plot_3.figure=plots['plot3']
    self.plot_4.figure=plots['plot4']

This should speed up the load time significantly.
The last call to dfa = anvil.server.call('get_dash') could be included in the above code somehow, for even more optimization.

Some reading for more info and tips:
https://anvil.works/forum/t/suggestions-to-optimize-performance/3318

6 Likes

You will have to first let us know where the problem happens. There can be two scenarios

  1. Your Website takes a long time to load. Most browsers usually show a loading spinner next to your tab to indicate that the website is still loading. Please do not confuse it with Anvil’s loading spinner.

  2. Your website doesn’t take too long to load but some actions take a long time.

The fix will be totally different for both scenarios.

1 Like

@ejl thank you very much.

My page just runs faster. Before it need almost 30sec to open now it just needs around 16-18 secs.

I tried dfa = anvil.server.call('get_dash') to get inside like this:
Server code: (Not tested code)

def get_plots():
  result = {
    "plot1": create_plots(),
    "plot2": create_plots2(),
    "plot3": create_plots3(),
    "plot4": create_plots4(),
   "dash": get_dash(),
  }
  return result

But it didn’t help much tho. I think this one is enough for now.

Thankyou for your time :grin: