C#实现页面加载
很多情况,我们的页面加载速度很慢,这时候就需要一个进度条来等待,增加用户友好性.
原理比较简单,在page_load的时候创建一个div,然后判断页面的加载装载状态,完成后消失.下面的代码:
原理比较简单,在page_load的时候创建一个div,然后判断页面的加载装载状态,完成后消失.下面的代码:
protected void Page_Load(object sender, EventArgs e)
{
Loading();
}
{
Loading();
}
Code
public void Loading()
{
HttpContext hc = HttpContext.Current;
//创建一个页面居中的div
hc.Response.Write("<div id='loading'style='position: absolute; height: 100px; text-align: center;z-index: 9999; left: 50%; top: 50%; margin-top: -50px; margin-left: -175px;'> ");
hc.Response.Write("<br />页面正在加载中,请稍候<br /><br /> ");
hc.Response.Write("<table border='0' cellpadding='0' cellspacing='0' style='background-image: url(images/Progress/plan-bg.gif);text-align: center; width: 300px;'> ");
hc.Response.Write("<tr><td style='height: 20px; text-align: center'><marquee direction='right' scrollamount='30' width='290px'> <img height='10' src='images/Progress/plan-wait.gif' width='270' />");
hc.Response.Write("</marquee></td></tr></table></div>");
//hc.Response.Write("<script>mydiv.innerText = '';</script>");
hc.Response.Write("<script type=text/javascript>");
//最重要是这句了,重写文档的onreadystatechange事件,判断文档是否加载完毕
hc.Response.Write("function document.onreadystatechange()");
hc.Response.Write(@"{ try
{
if (document.readyState == 'complete')
{
delNode('loading');
}
}
catch(e)
{
alert('页面加载失败');
}
}
function delNode(nodeId)
{
try
{
var div =document.getElementById(nodeId);
if(div !==null)
{
div.parentNode.removeChild(div);
div=null;
CollectGarbage();
}
}
catch(e)
{
alert('删除ID为'+nodeId+'的节点出现异常');
}
}
");
hc.Response.Write("</script>");
hc.Response.Flush();
}
public void Loading()
{
HttpContext hc = HttpContext.Current;
//创建一个页面居中的div
hc.Response.Write("<div id='loading'style='position: absolute; height: 100px; text-align: center;z-index: 9999; left: 50%; top: 50%; margin-top: -50px; margin-left: -175px;'> ");
hc.Response.Write("<br />页面正在加载中,请稍候<br /><br /> ");
hc.Response.Write("<table border='0' cellpadding='0' cellspacing='0' style='background-image: url(images/Progress/plan-bg.gif);text-align: center; width: 300px;'> ");
hc.Response.Write("<tr><td style='height: 20px; text-align: center'><marquee direction='right' scrollamount='30' width='290px'> <img height='10' src='images/Progress/plan-wait.gif' width='270' />");
hc.Response.Write("</marquee></td></tr></table></div>");
//hc.Response.Write("<script>mydiv.innerText = '';</script>");
hc.Response.Write("<script type=text/javascript>");
//最重要是这句了,重写文档的onreadystatechange事件,判断文档是否加载完毕
hc.Response.Write("function document.onreadystatechange()");
hc.Response.Write(@"{ try
{
if (document.readyState == 'complete')
{
delNode('loading');
}
}
catch(e)
{
alert('页面加载失败');
}
}
function delNode(nodeId)
{
try
{
var div =document.getElementById(nodeId);
if(div !==null)
{
div.parentNode.removeChild(div);
div=null;
CollectGarbage();
}
}
catch(e)
{
alert('删除ID为'+nodeId+'的节点出现异常');
}
}
");
hc.Response.Write("</script>");
hc.Response.Flush();
}