In JavaScript it is possible to wait for onLoad
which may be used to specify the time of page loading pletion.
Every HTTP response is sent along with Date:
header which contains the time server sent a response.
Is there a way in JavaScript to get the time of page started loading?
Something similar to response Date:
header.
It would be useful for cases when JavaScript is injected into page after some delay.
In JavaScript it is possible to wait for onLoad
which may be used to specify the time of page loading pletion.
Every HTTP response is sent along with Date:
header which contains the time server sent a response.
Is there a way in JavaScript to get the time of page started loading?
Something similar to response Date:
header.
It would be useful for cases when JavaScript is injected into page after some delay.
Share Improve this question edited Mar 2, 2014 at 11:18 nilfalse asked Jul 2, 2012 at 14:56 nilfalsenilfalse 2,4192 gold badges20 silver badges17 bronze badges 2- 3 The server can write the time into the response in a number of ways: JavaScript code, HTML attribute values, etc. – Pointy Commented Jul 2, 2012 at 14:59
- Are you looking for "server" date? – Salman Arshad Commented Jul 2, 2012 at 15:32
5 Answers
Reset to default 12new Date(performance.timing.connectStart)
in chrome, firefox, IE9, etc (caniuse)
demo
console.log(new Date(performance.timing.connectStart));
Try storing a value from var d= new Date(); var requested = d.getTime();
and execute it when the page loads.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var loadDate;
</script>
</head>
<body onload="loadDate=new Date();">
<button onclick="alert(loadDate);">show load Date</button>
</body>
</html>
Update 2023
As performance.timing.connectStart
is deprecated, I remend:
window.performance?.timeOrigin
Here is my code to get something bullet-proof:
const sessionStartDateTime = window.performance?.timeOrigin ?? window.performance?.timing?.connectStart ?? Date.now();
Sources:
- window.performance.timing deprecated
- https://developer.mozilla/en-US/docs/Web/API/PerformanceNavigationTiming
Hope ir helps :)
I would just pass a timestamp from the server-side script to the browser via a cookie or inline JS. E.g. in PHP:
<script>
var timestamp = new Date(<?php echo time(); ?>);
</script>