Home > OS >  How to calculate page load time using JQuery?
How to calculate page load time using JQuery?

Time:11-25

I'm writing my own site as homework and my teacher ask me to write a script that calculate page load time and write it on footer, I write it using JS, but I want to write it using Jquery, but I don't understand how to do it. Here is my code using JS:

let loadTime = (function () {
    let now = new Date().getTime();
    let page_load_time = now - performance.timeOrigin
    let time_load = page_load_time / 1000;
    return time_load.toFixed(4);
})();

CodePudding user response:

Try this :

var beforeload = (new Date()).getTime();

function getPageLoadTime() {
  var afterload = (new Date()).getTime();
  seconds = (afterload - beforeload) / 1000;
  $("#load_time").text('Loaded in  '   seconds   ' sec(s).');
}

window.onload = getPageLoadTime;
p {
  font-size:50px;
  text-align: center;
  font-family: HelveticaNeue, Helvetica, Arial, sans-serif;
  color: #000;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Check Time</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>
<body>

<p id="load_time"></p>

</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

No need to complicate easy function, use this

window.onload = function () {
    var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart; 
    console.log('Load time: '  loadTime);
}
  • Related