I'm building a web-based page render benchmark app which uses the Web Performance API. What it does is basically measuring how much time the browser takes when ordered to render a bunch of div elements, and then build a hidden form, put the calculation result in there, and submit the form to another PHP page for processing. The problem is, the calculation result keeps being negative and in the several trillion range (i.e. a fourteen digit number: -1364403484035). Here's the code:
window.onload=function(){
results=(performance.timing.loadEventEnd-performance.timing.responseEnd);
var browserData = document.createElement("form");
browserData.setAttribute("method","post");
browserData.setAttribute("action","results.php");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "res");
hiddenField.setAttribute("value", results);
browserData.appendChild(hiddenField);
document.body.appendChild(browserData);
browserData.submit();`
UPDATE 1:
I did some tweaking to my code, like this:
window.onload=function(){
// My edits
beginning=performance.timing.responseEnd;
ending=performance.timing.loadEventEnd;
results=(ending-beginning);
// End of my edits
var browserData = document.createElement("form");
browserData.setAttribute("method","post");
browserData.setAttribute("action","results.php");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "res");
hiddenField.setAttribute("value", results);
browserData.appendChild(hiddenField);
document.body.appendChild(browserData);
browserData.submit();`
And used the browser's JavaScript console to peek into the variables' values and I found that ending = 0
It is because loadEventEnd is set when the window.load is done. You are calling it in the load event!
The loadEventEnd property must return the time when the load event of the current document is completed. It must return zero when the load event is not fired or is not completed.
How to fix:
Use a setTimeout so the onload can end.
window.onload = function () {
window.setTimeout(function () {
results = (performance.timing.loadEventEnd - performance.timing.responseEnd);
var browserData = document.createElement("form");
browserData.setAttribute("method", "post");
browserData.setAttribute("action", "results.php");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "res");
hiddenField.setAttribute("value", results);
browserData.appendChild(hiddenField);
document.body.appendChild(browserData);
browserData.submit();
}, 0);
}
Another option is poll loadEventEnd
until it is not zero.