Ryan Detzel
Ryan Detzel

Reputation: 5599

How fast are cookies written when called from JavaScript?

We want to more accurately track internal clicks and since we're not guaranteed that the request will complete before the page loads I was thinking of immediately writing the value to a cookie and then reading it back on the next page load. I'm assuming the write time of cookies are very quick and would beat out any page load but I want to see if anyone has a specific number.

Also, does anyone see any flaws in this method?

Upvotes: 0

Views: 1175

Answers (2)

Neil
Neil

Reputation: 1206

The trick with cookies is that because they are stored on the client (browser), they way the server gets informed is through the HTTP payload (the headers and content of an HTTP request). What that means is the cookies will need to be set before the HTTP request you intend to retrieve them on.

You should have no problem with this method if your user is going from page to page at a a time. The [set] cookie headers will have processed before the user is shown the content for them to click.
Where using cookies to remember information might not work is with AJAX requests and cookies being set by JavaScript. There's a chance that the cookie may not yet be set before the AJAX is fired, and therefore won't be included in the header (payload).

Upvotes: 0

jfriend00
jfriend00

Reputation: 707696

Cookies like pretty much anything else that is local to your own computer are nearly always going to be faster than going over the internet to another web server. If you are writing them on one page load, they are immediately available right after you write them, even on the same page so they will always be there for the next page load too.

If you're trying to put a cookie in place for a server to see it, then it will be in place to be sent with future network requests as soon as you write the cookie, but obviously wouldn't have been sent as an HTTP header for any requests that were started before you wrote the cookie.

But, with anything, if this is critically important to you, then you should write your own type of benchmark and run it in a scenario of a typical user to actually measure the performance you care about and compare it to your alternative.

Upvotes: 1

Related Questions