How to find out what percentage of the page has lo

2019-06-02 11:37发布

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条回答
小情绪 Triste *
2楼-- · 2019-06-02 12:11

$(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" />
查看更多
登录 后发表回答