javascript: time until page load

眉间皱痕 提交于 2020-01-05 04:55:32

问题


i am writing a animation with javascript and want to print to user loading time until all images loaded.

images set in html as: <img src="" />

are there javascript code to know when all page loaded?
i.e time until onLoad() event called


回答1:


You might be able to do something like this at the bottom of the page

<span id="imgsMsg"></span>
<script type="text/javascript">
var imgs = document.images;
var len = imgs.length;
var percent = 100;
var count=0;
var messagecontainer = document.getElementById("imgsMsg");
for (var i=0;i<len;i++) {
   imgs[i].onload=function() {
     count++;
     messagecontainer = (percent - Math.floor((100/len)*count))+"% loaded"; // hope my math is correct ;)
   }
}
</script>
</body>



回答2:


The best you can probably do is to track the number of images that have been loaded, and divide that into the total number of images remaining. Something like this:

var total_loaded = 0;
$('img').load(function()
{
    total_loaded += 1;
    var load_progress = total_loaded / $('img').length;
    // you can now use load_progress to show the user a rough progress animation
} );

If you want a "time remaining" display, you'll need to fake it. You could track the total time elapsed and compare that to the load_progress variable to get the remaining time, for example.




回答3:


This isn't hard to do, with $(window).load:

var readytime = new Date().getTime();
$(window).load(function() {
    var loadingtime = (new Date().getTime() - readytime) / 1000; // in seconds

    $('#yourTimingField').text(loadingtime + ' seconds');
});

This measures the amount of time between the this part of the script and the loading of all subelements.



来源:https://stackoverflow.com/questions/4794627/javascript-time-until-page-load

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