Reputation: 41
I'm using a javascript in my html page.. I have been recording the time taken using the navigation API .. When I try to findout the total load time (navigationStart - loadEventEnd) I find that the loadEventEnd is 0 . But also found that the loadEventStart value is recorded .. I print these values on console inside window.onload = function() {} . . From the above stats I assume that my function is called after the load event has fired and before it has completed .. However using onunload function gives me the result , the result cannot be viewed as it is printed in the console and unload event is triggered when moving away from the page .. Please help me find a solution .
Upvotes: 2
Views: 10052
Reputation: 1669
Try the following. i hope it will also work... Use the window.onload object as follows:-
window.onload=function(){
//set of javascript statments...
}
or if you have any functions then use the window.onload as follows:-
window.onload=function_name
Have a look at the following example for better understanding of window.location
<html>
<head>
<script type="text/javascript">
window.onload = test;
function test(){
alert("hello");
}
</script>
</head>
<body>
<h5>Simple javascript test for page load</h5>
</body>
</html>
Upvotes: 0
Reputation: 1669
Use the onload attribute in the tag as follows:-
<body onload="methodName();">
Try the following example for better understanding:-
<html>
<head>
<script type="text/javascript">
function test(){
alert("hello");
}
</script>
</head>
<body onload="test();">
<h5>Simple javascript test for page load</h5>
</body>
</html>
Upvotes: 1
Reputation: 7067
Most likely you're getting a value of 0
because you're printing the information before the page has completed loading, try the following snippet:
window.onload = function(){
setTimeout(function(){
var t = performance.timing;
console.log(t.loadEventEnd - t.responseEnd);
}, 0);
}
That will make sure the numbers are printed after the page is actually ready. Got that snippet from here. Other information from that page you might find interesting:
Data from the API really comes to life when events are used in combination:
- Network latency ():
responseEnd-fetchStart
.- The time taken for page load once the page is received from the server:
loadEventEnd-responseEnd
.- The whole process of navigation and page load:
loadEventEnd-navigationStart
.
Upvotes: 1