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; }
However, further optimizations are possible.
Shortest and Most Efficient Solution:
const getCookieValue = (name) => ( document.cookie.match('(^|;)\s*' + name + '\s*=\s*([^;]+)')?.pop() || '' )
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:
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!