Home > Web Front-end > JS Tutorial > body text

How to Read Cookies in Javascript: Shortest, Fastest, and Most Reliable?

Susan Sarandon
Release: 2024-11-08 01:16:02
Original
565 people have browsed it

 How to Read Cookies in Javascript: Shortest, Fastest, and Most Reliable?

Concise Cookie Reading in JavaScript: Optimizing for Size and Performance

When working with stand-alone JavaScript scripts without external dependencies, finding the optimal solution for reading cookies is crucial. The QuirksMode.org readCookie() function, while functional, is bulky and inefficient.

Improved jQuery.cookie Approach:

The read_cookie() function used by jQuery.cookie is more compact than readCookie():

function read_cookie(key)
{
    var result;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}
Copy after login

However, further optimizations are possible.

Shortest and Most Efficient Solution:

const getCookieValue = (name) => (
  document.cookie.match('(^|;)\s*' + name + '\s*=\s*([^;]+)')?.pop() || ''
)
Copy after login

This approach leverages a regular expression to extract the desired cookie value, handling optional whitespace around the semicolon and equals sign. It also eliminates the need for multiple loops, making it significantly faster than other solutions.

Performance Comparison:

A performance comparison using jsben.ch demonstrates the superiority of the suggested solution:

https://jsben.ch/AhMN6

Key Advantages:

  • Concise: Only 18 characters (minified).
  • Reliable: Accounts for optional whitespace according to the official spec.
  • Performant: Significantly faster than other methods in most browsers.

The above is the detailed content of How to Read Cookies in Javascript: Shortest, Fastest, and Most Reliable?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!