1
mirror of https://github.com/jakejarvis/dark-mode.git synced 2025-04-25 17:35:21 -04:00

remove super-duper edge case testing of localStorage support

use the following methods externally to test on older browsers if needed:
- https://www.npmjs.com/package/storage-available
- https://www.npmjs.com/package/local-storage-fallback
- https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#testing_for_availability
This commit is contained in:
Jake Jarvis 2021-08-22 10:38:26 -04:00
parent 582e64ae13
commit fa128cb222
Signed by: jake
GPG Key ID: 2B0C9CF251E69A39
2 changed files with 3 additions and 20 deletions

View File

@ -4,7 +4,7 @@
[![npm (scoped)](https://img.shields.io/npm/v/@jakejarvis/dark-mode)](https://www.npmjs.com/package/@jakejarvis/dark-mode)
[![MIT License](https://img.shields.io/github/license/jakejarvis/dark-mode?color=violet)](LICENSE)
Very simple CSS dark/light mode toggler with saved preference via local storage & dynamic OS setting detection. Zero dependencies and [only ~600 bytes gzipped!](https://bundlephobia.com/package/@jakejarvis/dark-mode)
Very simple CSS dark/light mode toggler with saved preference via local storage & dynamic OS setting detection. Zero dependencies and [only ~500 bytes gzipped!](https://bundlephobia.com/package/@jakejarvis/dark-mode)
- [View the example.](https://jakejarvis.github.io/dark-mode/)
- [Read the blog post.](https://jarv.is/notes/dark-mode/)

View File

@ -1,5 +1,3 @@
"use strict";
const init = function (options) {
options = options || {};
@ -8,8 +6,7 @@ const init = function (options) {
// check for preset `dark_mode_pref` preference in local storage
const storageKey = options.storageKey || "dark_mode_pref";
const storageAvailable = isStorageAvailable();
const pref = storageAvailable ? localStorage.getItem(storageKey) : null;
const pref = localStorage.getItem(storageKey);
// change CSS via these <body> classes:
const dark = options.classes ? options.classes.dark : "dark";
@ -27,7 +24,7 @@ const init = function (options) {
document.body.classList.add(theme);
active = theme === dark;
if (storageAvailable && !!remember) {
if (remember) {
localStorage.setItem(storageKey, theme);
}
@ -93,18 +90,4 @@ const init = function (options) {
}
};
// recommended method (by MDN) to detect localStorage availability:
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#feature-detecting_localstorage
const isStorageAvailable = function () {
try {
var storage = window["localStorage"];
var x = "__storage_test__";
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch (e) {
return false;
}
};
export { init };