Тема: javascript
-
Хранилища браузера: сравнение cookie, Web Storage и IndexedDB
Cookie передаются с каждым запросом и по спецификации имеют небольшой размер. localStorage и sessionStorage — синхронные строковые хранилища с несколькими MiB на источник; IndexedDB асинхронна, поддерживает транзакции и использует большую общую квоту источника. Без предоставленной постоянности браузерное хранение выполняется по возможности и ограничивается источником.
-
Using fetch with timeouts and AbortController
A fetch promise rejects only on network failure, not on HTTP error status, and it has no timeout by itself. Pass an AbortSignal combined from AbortSignal.timeout and a caller's controller, check response.ok, and tell TimeoutError, AbortError, network errors and HTTP errors apart in the catch.
-
ES module builds with declared side effects shrink consumer bundles more than CommonJS builds
Hypothesis: for a library of many independent functions, a consumer that imports a few of them gets a smaller bundle when the library ships ES modules with a sideEffects declaration than when it ships CommonJS, because tree shaking depends on static import/export structure; a fixture-based comparison is proposed.
-
Веб-компоненты: пользовательские элементы, shadow DOM и границы инкапсуляции
Пользовательские элементы регистрируют класс под именем тега с дефисом и обратными вызовами жизненного цикла; shadow DOM даёт ему поддерево с изоляцией стилей в обе стороны, а шаблоны и декларативные теневые корни — разметку. Любое взаимодействие через границу, от стилизации через parts и пользовательские свойства до участия в формах через ElementInternals и связи с подписями, нужно открывать явно.
-
When does client-side routing still pay off now that browsers offer bfcache, prerendering and cross-document view transitions?
Open question: in-page routers were adopted to avoid full page loads, at the cost of shell serving, 404 handling, scroll and focus restoration and a bundle that must arrive first; the back/forward cache, the Speculation Rules API and cross-document view transitions now address the original motivations in multi-page sites. For which sites and interaction patterns does an in-page router still measurably win?
-
Интерфейс с учётом локали: Intl, формы множественного числа, даты и разметка справа налево
Форматируйте числа, даты и относительное время объектами Intl браузера, а не операциями со строками; выбирайте формы по категориям Intl.PluralRules вместо n == 1, используйте логические свойства CSS, чтобы документ с dir=rtl зеркально перестраивался, и оставляйте место для текста, удлиняющегося при переводе.
-
ES-модули и CommonJS в Node.js
CommonJS использует синхронный require и module.exports; ES-модули — статические import/export, await верхнего уровня и import.meta. Node определяет формат каждого файла по расширению и полю type ближайшего package.json. Для ES-модулей нужны полные расширения файлов; __dirname и require в них отсутствуют, но имеют документированные замены.
-
Смещения в тексте JavaScript: различайте кодовые единицы UTF-16, кодовые точки и видимые символы
Указывайте единицу смещения на каждой границе редактора или API и осознанно преобразуйте её перед выделением среза текста.
-
Rolling out a service worker safely: scope, versioned caches, the waiting worker and a kill switch
A service worker that caches HTML can pin users to old code after a deploy. Register it with an explicit scope, fetch the script fresh on every update check, version caches per build and delete old ones on activate, choose per-resource strategies, decide how the waiting worker takes over, and ship a tested kill switch before the first release.
-
Keyboard navigation in composite widgets: roving tabindex, arrow keys and Escape
Tab and Shift+Tab move between components; arrow keys move inside a component such as a tab list, toolbar, menu or radio group. Implement this with a roving tabindex (one item at tabindex=0, the rest at -1) or aria-activedescendant, close transient surfaces with Escape, and never trap focus without an advertised way out.
-
Focus management in single-page interactions: dialogs, route changes and removed elements
When a page changes without a full load, keyboard focus must be moved on purpose: into a dialog when it opens and back to its trigger when it closes, to the new view's heading after a client-side route change, and to a sensible neighbour when the focused element is deleted. Otherwise focus falls to the document body and screen-reader users are sent back to the top.
-
Обработка ошибок в Promise и async/await
Асинхронная функция превращает throw в отклонение промиса, а await повторно возбуждает ошибку; у каждого отклонения должен быть ответственный обработчик. Оборачивайте только операции, после которых можете восстановиться, не оставляйте промисы без обработки, используйте allSettled при допустимом частичном сбое и регистрируйте обработчик unhandledrejection как последнюю защиту.
-
The JavaScript event loop: tasks, microtasks and rendering
JavaScript runs one job at a time; the HTML event loop takes a task, then drains the whole microtask queue (promise reactions, queueMicrotask) before the next task or a rendering opportunity. Long synchronous work and endless microtask chains block input and painting.
-
BigInt в JSON: определите контракт полей без потерь, прежде чем добавлять replacer
Кодируйте большие целые числа по явной схеме и восстанавливайте их без незаметного промежуточного преобразования в Number.
-
Битовые операции без сюрпризов: флаги, маски и сдвиги
Флаги — степени двойки: их объединяют операцией ИЛИ, проверяют операцией И и сбрасывают операцией И с НЕ; маски и сдвиги извлекают поля. Ловушки — приоритет операторов, знаковые правые сдвиги, преобразование к 32 битам в JavaScript и неограниченные целые Python. Давайте имя каждому флагу и заключайте каждую проверку в скобки.
Машиночитаемо: JSON