开发者

How can I know how long the current page has been loaded using Jquery or Javascript?

How can I know how long the current page has been loa开发者_JAVA百科ded using Jquery or Javascript? What function?


When the page loads get the current timestamp:

var startTime = new Date().valueOf();

Then the page has been loaded for the current timestamp minus this value:

var loadedSeconds = (new Date().valueOf() - startTime) / 1000;

The time is in milliseconds so divide by 1000 to get seconds.

Example Code :-

<script>
//Getting Date When Page Started Loading
var start = new Date();

//Window Load Function that is called after page is completely loaded
$(window).load(function() {

//Substracting Started Time From Time When Page Completely Loaded
   $('body').html(new Date() - start); 
});
</script>


The Web Animations API provides document.timeline, which has a currentTime property with the age of the page (technically, it starts counting when you navigate away from the previous page).

console.log(`This page has existed for ${document.timeline.currentTime} milliseconds.`);

Note that this feature is pretty new. Chrome only added it in July of 2020, so if you need to support older browsers then your best bet is to use one of the other solutions provided on this page.


You can do a var start = new Date(); in the beginning of your <head> then, at the end of the <body>, do a new Date().getTime() - start.getTime()


Those solutions tell you how long it has taken a page to load.

To tell how long the page has been running for you could run a function that finds the time (using the methods the other guys have mentioned) displays the time, and then calls itself (after maybe a small pause).

This is going to be a fairly intensive process and I wouldn't suggest doing it on a site that many visitors, or one that requires other JS to be running.

EDIT - Actually if you make it a button that you click to call the function and don't have it calling itself that would stop any crazy overheads.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜