简体   繁体   中英

asp.net page first load - show loading div before everything

I have an asp page. on first load of the page, the function Page_Load takes long time to finish (15 seconds) and I can't make it shorter.

I want to achieve this:

First thing the page shows, before everything, is a div with the word loading. Then after the Page_Load finishes I want to make this disappear.

How can this behavior be achieved?

You could have a loading msg panel and a content panel. This would allow the Page to first render a loading message and then invoke the request for the long request

void Page_Load(){
    var fromMsg = Request["loading"] == "1";
    if (!fromMsg) {
       LoadingPanel.Visible = true;
       ContentPanel.Visible = false
    } else {
       // Load Heavy Content Here
    }
}

Then in your Loading Panel just add some javascript to invoke a reload

<asp:Panel id="LoadingPanel" runat="server" Visible="false">
    <h2>Loading...</h2>
    <script type='javascript'>
    window.setTimeout(function(){
       location.href = location.href += "&loading=1";
    }, 400);
    </script>
</asp:Panel>
<asp:Panel id="ContentPanel" runat="server">
   ...
</asp:Panel>

If the loading message is simple you can accomplish the same thing in the CodeBehind with something simple like

void OnInit() 
{
    var fromMsg = Request["loading"] == "1";
    if (!fromMsg) {
       Response.Clear();
       Response.Write("<h2>Loading....</h2>");
       Response.Write("<script type='text/javascript'>window.setTimeout(function(){ location.href = 'ThisPage.aspx?loading=1'; }, 400);
       Response.End();
    }
}

If you needed to do this on a lot of pages you could create a Helper library to generate the MessageHtml and set the refresh JS with ScriptManager

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM