Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Your best snippets Reply To: Your best snippets

#248761
Shikkediel
Participant

Edited…

This one supposedly has an issue with Safari and private browsing mode – may need an update.

Having done a search across the net and not really liking any of the answers here much because accessing storage to check it’s presence just doesn’t seems like the right approach, I tested and made another snippet that checks the availability of web storage but still detects whether it happens to be disabled.

Based on this article:

Link

var depot = (function() {
  try {
  return localStorage;
  }
  catch(e) {}
})();

Besides having a variable that can be used inside an if statement as a possible falsy, storage itself will also be cached and usable.

if (depot) {
  depot.setItem ...
}

Another thing about the mostly accepted approach that Modernizr also uses is that Mozilla docs state that localStorage is synchronous in nature. This can block rendering of the main document unless you wait for it to be ready. With the above snippet, there’s no need to be concerned about that either.