How to find out what percentage of the page has loaded in order to update the jQuery UI progressbar ?

一笑奈何 提交于 2019-12-23 03:24:25

问题


I have a huge xml file which i am transforming using xslt. I am also doing a lot of stuff using jquery on page load. Basically hiding a lot of divs and opening them up after onclick. Because of this the page load takes like 2-3 seconds now.

I thought it would be good to show a progressbar while it loads so the user knows that the page is getting loaded instead of them staring at a white screen. When looking up the jquery UI progressbar i found out that it has a value attribute which determines the length of the bar.

$( "#progressbar" ).progressbar({ value: 37});

Now as i already told my js file has one huge $(document).ready(function() { ...... }); which loads the whole page. How do i get that value of how much the page has loaded so that i can pass it to the value attribute of the progressbar ?


回答1:


$(document).ready doesn't fire until the DOM is loaded, so this won't be much help.

Given that you don't know how big the document will be (in your JavaScript) this will be hard to do accurately.

One solution might be to included some information at the top of the file that indicates how may elements to expect. You could then count the elements in the DOM and get an idea of how complete you are.

You could use a timer or interval to start looking before the document is ready and keep going until you hit 100%;

if (document.getElementById('expected')) {
    var expected = parseInt(document.getElementById('expected').value, 10);
    var loaded = document.getElementsByTagName('div');
    var progress = (loaded / expected) * 100;
}

You would need the expected element close to the top of the page.

<input type="hidden" id="expected" value="50" />


来源:https://stackoverflow.com/questions/13182282/how-to-find-out-what-percentage-of-the-page-has-loaded-in-order-to-update-the-jq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!