The webpage progress bar can better reflect the loading progress of the current webpage. The loading progress bar can be animated from 0% to 100% to complete the webpage loading process. However, current browsers do not provide an interface for page loading progress, which means that the page cannot accurately return the actual loading progress of the page. In this article, we use jQuery to achieve the page loading progress bar effect.
HTML
The first thing we need to know is that currently no browser can directly obtain the size of the object being loaded. Therefore, we cannot achieve 0-100% loading and display process through data size.
Therefore, we need to use the line-by-line loading feature of html code, set nodes in several skip lines of the entire page code, and provide approximate fuzzy progress feedback to achieve the effect of progress loading. The general meaning is: every time the page is loaded into the specified area, the progress result of (n)% is returned. By setting multiple nodes, the purpose of displaying the loading progress step by step is achieved.
If there is a page, it is divided into four parts according to the block: header, left content, right sidebar, and footer. We regard these four parts as four nodes. When the page loads each node, set the approximate loading Percentage, the page structure is as follows:
<div id="header"> 页头部分 </div> <div id="mainpage"> 左侧内容 </div> <div id="sider"> 右边侧栏 </div> <div id="footer"> 页脚部分 </div>
Then we add the progress bar.loading to the first line under
.<div class="loading"></div>
CSS
We need to set the style of the loading progress bar, set the background color, height, position, priority, etc.
.loading{ background:#FF6100; //设置进度条的颜色 height:5px; //设置进度条的高度 position:fixed; //设定进度条跟随屏幕滚动 top:0; //将进度条固定在页面顶部 z-index:99999 //提高进度条的优先层级,避免被其他层遮挡 }
jQuery
Next, we need to add progress animation behind each node and use jQuery to implement it.
<div id="header"> 页头部分</div> <script type="text/javascript"> $('.loading').animate({'width':'33%'},50); //第一个进度节点 </script> <div id="mainpage"> 左侧内容 </div> <script type="text/javascript"> $('.loading').animate({'width':'55%'},50); //第二个进度节点 </script> <div id="sider"> 右边侧栏 </div> <script type="text/javascript"> $('.loading').animate({'width':'80%'},50); //第三个进度节点 </script> <div id="footer"> 页脚部分 </div> <script type="text/javascript"> $('.loading').animate({'width':'100%'},50); //第四个进度节点 </script>
It can be seen that after not loading a node, jQuery calls the animate() animation method to change the width of the progress bar. Each node change takes 50 milliseconds to make the progress bar look smoother, and finally changes from 0% to 100%, the progress animation of the progress bar is completed.
When the progress bar reaches 100%, the page is loaded. The last step to do is to hide the progress bar.
$(document).ready(function(){ $('.loading').fadeOut(); });