You-Dont-Need-jQuery README

The project's README from github.com/camsong/You-Dont-Need-jQuery. As one markdown file: README.md.

You (Might) Don't Need jQuery

Frontend environments evolve rapidly nowadays and modern browsers have already implemented a great deal of DOM/BOM APIs which are good enough for production use. We don't have to learn jQuery from scratch for DOM manipulation or event handling. In the meantime, thanks to the spread of frontend libraries such as React, Angular and Vue, manipulating the DOM directly becomes anti-pattern, so that jQuery usage has never been less important. This project summarizes most of the alternatives in native JavaScript implementation to jQuery methods.

Snippets target current evergreen browsers (Chrome, Edge, Firefox, Safari). Internet Explorer is no longer supported by Microsoft, so IE-specific fallbacks have been removed. If you still need them, see the last IE-compatible version.

ℹ️ Notice:

  1. jQuery is still a great library and has many valid use cases. Don’t migrate away if you don’t want to!
  2. The alternatives are not completely equivalent in all scenarios, and it is recommended that you test it before using it.

Table of Contents

  1. Translations
  2. Query Selector
  3. CSS & Style
  4. DOM Manipulation
  5. Ajax
  6. Events
  7. Utilities
  8. Promises
  9. Animation
  10. Alternatives
  11. Browser Support

Translations

Query Selector

In place of common selectors like class, id or attribute we can use document.querySelector or document.querySelectorAll for substitution. The differences lie in:

Notice: document.getElementById, document.getElementsByClassName and document.getElementsByTagName are slightly faster than querySelector*, but getElementsBy* return a live HTMLCollection that changes as the DOM changes. Prefer querySelector* unless you have measured a bottleneck.

⬆ back to top

CSS & Style

⬆ back to top

DOM Manipulation

⬆ back to top

Ajax

Fetch API is the standard replacement for XMLHttpRequest and works in all modern browsers. Unlike $.ajax, fetch does not reject on HTTP error status such as 404 or 500; check response.ok yourself. For JSONP, try fetch-jsonp.

⬆ back to top

Events

⬆ back to top

Utilities

Most of jQuery utilities are also found in the native API. Other advanced functions could be chosen from better utilities libraries, focusing on consistency and performance. Lodash and es-toolkit are recommended replacements.

⬆ back to top

Promises

A promise represents the eventual result of an asynchronous operation. jQuery has its own way to handle promises. Native JavaScript implements a thin and minimal API to handle promises according to the Promises/A+ specification, and async/await makes them read like synchronous code.

⬆ back to top

Animation

The Web Animations API (el.animate()) is the closest native match to jQuery effects: it takes a duration in milliseconds, runs off the main thread where possible, and returns an Animation whose finished promise resolves when it ends.

Alternatives

Browser Support

Chrome Edge Firefox Safari Opera
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔

A few snippets use newer APIs: Promise.withResolvers() (2024), el.replaceChildren() (2020) and AbortSignal.timeout() (2022). Check Baseline if you support older browsers.

License

MIT

You-Dont-Need-jQuery (camsong/You-Dont-Need-jQuery)

Searching Database…

Что это такое?Справочник, который показывает эквивалент на чистом JavaScript (нативные API DOM/BOM) для распространённых методов jQuery: поиск элементов, стилизация, работа с DOM, ajax, события, утилиты, промисы и анимация.
Это библиотека, которую нужно установить, или просто справочный документ?Это не библиотека для установки, а сборник документации и фрагментов кода, организованный по темам (селекторы, CSS, DOM, Ajax, события, утилиты, промисы, анимация), из которого вы копируете подходы.
Как этим пользоваться?Просмотрите оглавление, найдите нужную функцию jQuery (например, query selector, ajax, события) и скопируйте рядом показанный фрагмент на чистом JS.
Нужен ли мне jQuery или любая другая библиотека, чтобы использовать эти фрагменты?Нет, в этом и смысл: фрагменты используют только нативные API браузера, например querySelector, fetch и Web Animations API.
Будет ли каждый фрагмент работать точно так же, как метод jQuery, который он заменяет?Нет, сам проект предупреждает, что альтернативы не полностью эквивалентны во всех сценариях, поэтому перед использованием в продакшене их нужно протестировать.
Этот проект всё ещё поддерживает Internet Explorer?Нет, специфичные для IE запасные варианты удалены после того, как Microsoft прекратила поддержку; при необходимости в README есть ссылка на старую версию, совместимую с IE.
Нужно ли полностью перестать использовать jQuery после прочтения этого?Нет, в README прямо сказано, что jQuery по-прежнему отличная библиотека с обоснованными сценариями использования, так что при желании её можно продолжать использовать.
Есть ли здесь замены для Ajax?Да, в качестве стандартной замены XMLHttpRequest рекомендуется Fetch API; при этом отмечается, что в отличие от $.ajax, fetch не отклоняет промис при HTTP-ошибках статуса вроде 404 или 500.
А как насчёт служебных функций jQuery, например extend или each?Большинство из них сопоставлены с нативными аналогами (Object.assign/spread, методы массивов), а для более сложных утилит руководство рекомендует Lodash или es-toolkit.
Как здесь обрабатываются анимации без jQuery?Рекомендуется Web Animations API (el.animate()) как наиболее близкий нативный аналог эффектов jQuery; он работает вне основного потока и возвращает промис finished.
Creator
camsong
Size
0.9 MB
Stars
20.1K
Age
10y
Commits · 90 Days