简体   繁体   中英

Time to first byte with javascript?

Is there any modern browser that via javascript exposes time to first byte (TTFB) and/or time to last byte (TTLB) on a http request without resorting to any plugin?

What I would like is a javascript snippet that can access these values and post them back the the server for performance monitoring purposes.

Clarification: I am not looking for any js timers or developer tools. What I wonder and hoping is if there are any browsers that measures load times and exposes those value via javascript.

What you want is the W3C's PerformanceTiming interface. Browser support is good (see this survey from Sep 2011). Like you speculated in response to Shadow Wizard's answer, these times are captured by the browser and exposed to javascript in the window object. You can find them in window.performance.timing . The endpoint of your TTFB interval will be window.performance.timing.responseStart (defined as "the time immediately after the user agent receives the first byte of the response from the server, or from relevant application caches or from local resources"). There are some options for the starting point, depending on whether you're interested in time to unload the previous document, or time to resolve DNS, so you probably want to read the documentation and decide which one is right for your application.

I fear it's just not possible.

JavaScript becomes "active" only after part of the request has been sent from server, accepted by the browser and parsed.

What you ask is kind like asking "Can I measure the weight of a cake after eating it?" - you need to first weight and only then eat the cake.

You can see the response time in the Chrome Developer Tools.

It's impossible to get the true TTFB in JS, as the page gets a JS context only after the first byte has been received. The closest you can get is with something like the following:

<script type="text/javascript">var startTime = (new Date()).getTime()</script>

very early in your <head> tag. Then depending on if you want to check when the html finishes, or everything finishes downloading, you can either put a similar tag near the bottom of your html page (and subtract the values), and then do an XHR back to the server (or set a cookie, which you can retrieve server side on the next page request) or listen to the onload event, and do the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM