Jquery и javascript в чем разница
Перейти к содержимому

Jquery и javascript в чем разница

  • автор:

jQuery vs. Vanilla JS

The Internet is packed with articles either questioning the necessity of jQuery or criticizing its very existence. What I’m trying to do in this article is not just to jump on the bandwagon. I’m also not going to tell you to go back through everything you’ve ever created using jQuery and update it to use vanilla JavaScript. Instead, I’d like for you to keep the following in mind for any future projects and, if you feel the benefit is worth the effort, update anything old that would benefit from the performance improvements.

Let’s take a look at jQuery’s description of itself, pick out what’s worth discussing, and do some inspection of the claims that it makes.

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

According to the test tables on the Vanilla JS website, jQuery (unknown version) is massively slower than plain ol` JavaScript. At least in terms of selecting elements from the DOM.

Syntax code operations / second
JavaScript document.getElementById(‘some-id’) 12,137,211
jQuery $(‘#some-id’) 350,557
JavaScript document.getElementByTagName(‘span’) 8,280,893
jQuery $(‘span’) 19,449

I’m not going to run the tests myself here, but it is worth pointing out that there are two major native DOM methods missing here: querySelector and querySelectorAll . These two would be the slowest operations, though still faster than jQuery.

Small

A minified copy of jQuery 3.2.1 is over 84 KB (35 KB GZipped). Is this small? Well, small compared to what?

What you consider small is rather subjective. I would say that this is outrageous for a simple “Hello, world” site, but perfectly understandable on massive, JavaScript heavy site.

Still, to compare, even if only jokingly…

A fully commented, unminified copy of Vanilla JS:

Feature-rich

The simple fact of the matter is that jQuery is limited in features by JavaScript, but JavaScript is not limited by jQuery. It is true that many of the methods in JavaScript were inspired by what was found in jQuery, but there are many things that JavaScript does that jQuery simply cannot. Take, for example, Mutation Observers, which allow you to watch an element for changes to the DOM, such as added or removed nodes and attribute changes.

And, yes, since jQuery is JavaScript, anything JavaScript can do is still possible in jQuery, but if you’re only going to use jQuery for selecting elements from the DOM to use in regular JavaScript, you’re being extremely inefficient and really only making things more difficult on yourself.

jQuery isn’t really used for anything that it adds to JavaScript though, but rather because it’s considered easy to use. Is it really easier to use though? Often times, not really.

Let’s assume a $ function as an alias for document.querySelector and see what we can do with it.

jQuery certainly does have the advantage when it comes to working with multiple elements.

Animation

Animations are the best and worst part of jQuery. jQuery’s .animate method provides some pretty impressive capabilities, while still being fairly easy to author.

CSS3 has transitions and animations, but those are very limited. Without JavaScript, it would be difficult or impossible for clicking on one element to cause an animation in another. And animating something like opacity from it’s computed value for an element is currently impossible.

If you need to animate something that isn’t triggered by :hover or some other pseudo class, you’re just going to have to do it in JavaScript.

The problem with jQuery’s animations is that, to the best of my knowledge, all of them work by adjusting the style of an element over the duration of the animation. While this gets the job done, it is computationally expensive and completely destroys jQuerys claim at being fast. Not only is this not taking advantage of the GPU, but it is having to re-calculate the computed style at every frame of the animation, and it involves writing to the DOM.

You might not notice any performance issues on a simple fadeIn , but you’d better be conservative in both the quantity and complexity of your animations.

But jQuery is far from the only way to do animations in JavaScript. There are better animation libraries out there, but the best way to do animations is JavaScript’s very own Animations API

This API is the most performant way to script animations, and it can animate virtually any CSS property, including CSS filters

Event handling

Not too much to say here. Handling events is pretty similar either way.

Again, jQuery’s advantage is that it makes attaching the same handler on multiple elements a lot cleaner and easier.

There are some differences though for more advanced cases. jQuery.on can have a few additional arguments, such as data . element.addEventListener , on the other hand, allows for the third parameter (commonly thought of as useCapture ) to be an object with keys for capture , once (removes listener after fired), and passive .

First, can we please give this technique a new name? “Asynchronous JavaScript And XML” is no longer fitting since JSON has almost entirely replaced XML these days. I guess AJAJ just doesn’t sound as cool.

Ever since fetch became available, and especially since async / await , $.ajax should just be avoided entirely if you’re tranpiling your code and make use of polyfills, as you really ought to be doing anyways.

Impact

There is no question that jQuery has been a major contributor in making the web what it is today. When JavaScript was in its infancy, jQuery was there to assist developers in writing a single script that dealt with all of the browser inconsistencies.

Even today, it’s not uncommon to have a JavaScript question on Stack Overflow answered with jQuery.

11 years after it’s initial release, it is still dominating the web, and developers are still talking about it (though, lately, in a more similar context to Flash).

It’s everywhere. It has influenced JavaScript itself. It made JavaScript more approachable in the darkest old days of JavaScript’s history, greatly impacting the adoption of the use of JavaScript, it’s popularity amongst developers, and made it possible for developers to remain sane while writing JavaScript.

Introducing esQuery

Every article I’ve seen on this subject creates a false dichotomy, in a sense. jQuery was / is popular for a reason. There are still plenty of ways that it is easier to use than vanilla JavaScript. But, not using jQuery doesn’t have to mean not using a JavaScript library at all.

esQuery is a library that I’ve been working on for a while now that aims to be the best of both worlds. It is what jQuery might have been, had it been created today instead of decades ago.

Weighing in at just under 3 KB when compressed, it is a modern JavaScript library that offers the majority of features of jQuery, quite a few of its own, and might just offer better performance in some circumstances than regular JavaScript since it is almost entirely asynchronous.

What is the difference between JavaScript and jQuery? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 9 years ago .

What is the main difference between JavaScript and jQuery. I know the minor difference like jQuery is high performance more reliable.

Stephen Ostermiller on Strike's user avatar

6 Answers 6

jQuery is a JavaScript library.

Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:

JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.

JavaScript vs JQuery

Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms. JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.

JavaScript or jQuery: which one should I use?

Ashish

A web developer at some point of time, always asks this question to himself, what should I code in: jQuery or JavaScript? A few beginner web developers want to know the exact difference between the two.

JQuery and JavaScript are actually the same. JQuery is a group of JavaScript libraries designed for DOM operations in HTML page such as animation, event handling, traversing and Ajax interactions.

A strong hold on JavaScript is necessary to use either of the two scripting languages. Therefore, in case you have just started out, please get a basic understanding of JavaScript. Then you will find jQuery does the same as JavaScript, but requires fewer lines of code than traditional JavaScript requires.

We can now do a comparison study of both these scripting language and suggest which one to use for your next web development project.

JavaScript

JavaScript is a scripting language used to make web pages more dynamic and have increased user interactions.

JavaScript is used in most websites and apps, most popular being Gmail and Facebook. The dynamic nature of websites which changes a section of the page without reloading the entire page is accomplished by JavaScript. Another cool example of what JavaScript can do is detecting whether the visitor of a website is opening the link in a computer or in mobile. We can then render mobile version of the website if visitor is using mobile.

JavaScript has endless use cases where it has changed the way people interact with web sites. Also, it is not limited to just website building, JavaScript is very actively used for server side development (example: node.js), desktop applications, developing dynamic games, etc.

There was a time few years back, when JavaScript was rendered differently by different web browsers, so it was a pain for web developers to code in JavaScript and make it work similarly across all popular browsers. This has changed now, as new standards by W3C now force all web browsers to implement JavaScript uniformly. This makes the developers life easier by not wasting time debugging the code trying to make it work for on particular web browser.

JQuery

JQuery is fast, small, and feature-rich JavaScript library. It handles all cross-browser issues itself. jQuery is also called a framework of JavaScript.

Doing HTML DOM (document object model) traversal, manipulation, animation, event handling, and Ajax has become so simple using jQuery. Also, it makes the same code works uniformly also across all web browsers. Write less do more is the motto of jQuery.

JQuery is very simple to grasp and even easier to use, therefore its learning curve is very small. JavaScript code here are couple of other JavaScript based libraries for example, MooTools, but jQuery is the most popular because it is so easy to use and extremely powerful.

Actually, JavaScript and jQuery are not two separate programming languages. Instead, they have the same JavaScript code underneath. The real difference lies in the way a developer uses them while coding. JQuery has been coded and improvised to perform most common scripting functions while using very few lines of code. Therefore, what it takes 10 lines to a task using JavaScript can be done in 2 lines using jQuery just by calling the relevant jQuery function.

Let’s look at a basic ‘mouse click event’ example:

Suppose we have an input element for a button and we want to listen to the mouse click event on this button, and get notified by an alert box message.

Here is how one would do it on JavaScript:

document.getElemementById(“mybutton”).addEventListener(‘click’, function()<

alert(“Hey, You clicked me ?”);

>);

The same thing can be don’t in jQuery using the following line of code.

Another example, a quick web app:

Ajax is Asynchronous JavaScript and XML. It is basically a collection of web development techniques used on the client-side to create asynchronous web apps. XMLHttpRequest (XHR) is JavaScript Object used to send HTTP requests to a web server and load the server response back into the script. This response can then be processed by the client.

Here we are building a simple app which sends request to the server to get the current date and time and once the response arrives, the response is displayed in a <div> tag already added to the HTML page. Let us see how different its coding would be when coded with JavaScript and when coded in jQuery.

Here is a server side script in php saved with name getDateTimeServerScript.php , that returns the current date and time.

JavaScript Version:

This is the JavaScript Version of the webpage (JavaScript.html):

<!DOCTYPE html>

<html>

<head>

<script>

function loadCurrentDateTime() <

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() <

if (xhttp.readyState == 4 && xhttp.status == 200) <

document.getElementById(“resultarea”).innerHTML = xhttp.responseText;

>

>

xhttp.open(“GET”, “getDateTimeServerScript.php”, true);

xhttp.send( );

>

</script>

</head>

<body>

<button type=”button” onclick=”loadCurrentDateTime()”>Load Current Date Time</button>

<div >

</body>

</html>

JQuery Version:

This is the jQuery version of the same webpage (JQuery.html).

The above written JavaScript and jQuery codes are doing the same thing, but javascript is doing it bu creating a XMLHttpRequest object and then processing the request by sending it to server and then displaying the response back in the “resultarea” div.

Whereas, in jQuery code the same thing, is being done by the jQuery library which was included into the code using the line

This library offers various pre-build functions for AJAX. One of them being $.ajax. The parameters of the request were passed and the response is collected in its callback function success.

Output Screenshots of web app example:

This screen shot show the JavaScript version of the web app.

This page has a button which when clicked initiates a request to the server, which calculates the current date and time, and send it back to client as response. This response is then added to a already defined <div> tag and displays the date and time. This date and time is according to “Asia/Calcutta” time zone as defined in the server side script mentioned above.

Here is another screenshot displaying the output of jQuery version of the web app.

As expected, Output of both JQuery and JavaScript version is the same. Difference lies in the internal implementation of the code.

What’s best for my project?

The most important point to consider before jumping to a conclusion of which language to use is since both JavaScript and jQuery are internally the same, any of them can be used to recreate the same effect as done by other’s code. Therefore, there is no point in spending lot of tie discussion whether JavaScript or jQuery is appropriate in a particular project or task.

However, if one has to choose one language of choice, jQuery is usually more than sufficient for all web based applications and projects, and therefore, jQuery holds the winning flag as it can do the same task in lesser number of lines of code as compared to core JavaScript code.

If you are a novice developer, you should actually spend lot of time grasping all the concepts of JavaScript and build few projects using core JavaScript and refrain from using jQuery initially. It is really useful to first understand how JavaScript interacts with the structure of a HTML page and how it can work in different possible scenarios.

Conclusion

jQuery makes things so simple and precise that it save time and speeds up the development time and lets developer focus more on the implementing the business logic that the project is supposed to do. However, it is advisable to study both languages deeply and thoroughly and decide yourself which one to use depending on given scenario.

My Name is Ashish @ashish_fagna. I am a software developer . If you enjoyed this article, please recommend and share it! Thanks for your time.

Разбираемся в Проблеме Пары JavaScript jQuery

Разбираем JavaScript jQuery. Узнайте, что такое библиотека jQuery и зачем она нужна. Что лучше начать учить первым JavaScript или jQuery?

Автор: Laura M. - Chief Editor

Обновлено: February 23, 2023

Разбираемся в Проблеме Пары JavaScript jQuery

Когда вы только начинаете изучать веб-разработку, то замечаете, что со временем перед вами открывается всё больше возможностей для создания сайтов, в том числе интерактивных. Как только вы обретаете необходимые знания и навыки, то различные интерактивные элементы, оптимизация загрузок и другие аспекты интерактивности уже не кажутся вам чем-то необычным, а становятся обыденностью или даже необходимостью. Поэтому как бы вы не осваивали разработку – в учебном заведении, онлайн или с помощью самообучения – вы должны понимать, что лучшим вариантом для реализации интерактивных возможностей является JavaScript. Ведь всё же, это язык Интернета! Но, что если я подскажу вам другой вариант? В этом руководстве мы постараемся рассмотреть известную всем пару JavaScript jQuery, а также рассказать об их соперничестве.

Для начала мы поговорим о каждом из них в отдельности – для чего они используются, их преимущества и недостатки. Позднее, как только мы узнаем о них более подробно, мы приступим к сравнению этих двух инструментов с различных точек зрения – доступности кода, карьерных возможностей и много другого. Итак, давайте сразу же перейдём к теме нашего руководства!

Содержание

Проблема Пары JavaScript jQuery

Когда вы ищете ответ на вопрос о реализации какой-либо функции с помощью JavaScript на различных форумах, то часто встречаете похожий на этот ответ ‘просто используй для этого jQuery’.

Но, что такое jQuery? Вы думали, что для этого необходим лишь JavaScript, но появилась альтернатива? Теперь вы хотите узнать больше про дилемму JavaScript jQuery.

Или, возможно, ваша ситуация совсем иная. Кто-то порекомендовал вам воспользоваться jQuery для вашего сайта, но вы недавно узнали, что JavaScript может сделать то же самое что и jQuery и даже больше.

Теперь вы спрашиваете, разве JS это необходимость для вас? Почему нельзя просто воспользоваться готовым кодом jQuery?

Давайте остановимся на этом моменте — будет ли для вас сюрпризом то, что JavaScript и jQuery на самом деле даже близко не являются двумя различными вариантами?

Самые Полюбившиеся Статьи

Ищете более подробную информацию по какой-либо связанной теме? Мы собрали похожие статьи специально, чтобы вы провели время с пользой. Взгляните!

Что Такое Дополненная Реальность: Разбираемся в Работе AR

Что Такое Дополненная Реальность: Разбираемся в Работе AR

Понимание, что такое дополненная реальность будет важным для изучения новейших технологий. Прочитайте руководство, чтобы узнать необходимую информацию!

How to become a teacher: teacher in classroom

Как Стать Учителем: Со Степенью и Без Неё

Мечтаете стать преподавателем? Узнайте, как стать учителем со степенью и даже без неё, а также быть частью сообщества учителей.

Python или C++: что лучше? Давайте узнаем!

Python или C++: что лучше? Давайте узнаем!

После прочтения этой статьи у вас сложится полное понимание того, какой язык программирования вам лучше выбрать Python или C++.

jQuery Это JavaScript

Некоторые представляют проблему выбора между JavaScript и jQuery как выбор между двумя различными технологиями, но на самом деле jQuery является лишь другим способом использования JavaScript. Да, JS это jQuery и наоборот

jQuery часто называют фреймворком или библиотекой, хотя и довольно самодостаточной. Итак, давайте более подробно разберёмся с самим JavaScript.

JavaScript

JavaScript — это язык программирования браузера, или по крайней мере он был таковым до недавнего времени – теперь его возможности и применение разрослись далеко за пределы окна браузера. Например, он используется для написания кода серверной части проекта.

В своем основном предназначении в качестве клиентского языка программирования, записанного в каждом интернет-браузере, он отвечает за интерактивные и динамические элементы на веб-странице, такие как прослушивание и реагирование на действия пользователя.

Тогда, что такое jQuery?

Что Такое jQuery?

Как уже упоминалось, jQuery является библиотекой JavaScript. Это означает, что библиотека jQuery представляет собой коллекцию JavaScript-кода, упакованного вместе, что позволяет получить к нему доступ без необходимости в ручном написании кода. Необходимо лишь добавить простую строчку кода, чтобы внедрить в код JavaScript какую-либо функцию, заранее подготовленную в jQuery.

Если вы знакомы с фреймворком Bootstrap, то хорошей аналогией для вас будет отношение между CSS и Bootstrap. Bootstrap является своего рода коллекцией CSS-команд, которые делают процесс стилизации страниц более быстрым и простым. jQuery для JavaScript, то же что и Bootstrap для CSS.

Различия JavaScript и jQuery в Коде

jQuery

Первый урок в ‘Интерактивном курсе по jQuery‘ от BitDegree очень наглядно показывает различие между кодом JavaScript jQuery.

Примером является HTML-кнопка, которая позволяет открывать и закрыть форму для входа.

Вот код JavaScript:

const login = document.getElementById(«login»);
const loginMenu = document.getElementById(«loginMenu»);
login.addEventListener(«click», () => <
if(loginMenu.style.display === «none») <
loginMenu.style.display = «inline»;
> else <
loginMenu.style.display = «none»;
>
>);

А вот так выглядит код jQuery:

Что заняло 9 строк кода с JavaScript, для jQuery потребовало лишь 3.

Вы когда-либо хотели узнать, какие платформы для онлайн обучения лучше всего подходят для вашей карьеры?

jQuery Лучше?

Ответ кажется очевидным, да? Просто используйте jQuery.

Это могло быть так пару лет назад, но в 2018 и текущем году актуальность jQuery в веб-разработке снижается, и примеры, подобные приведенному выше коду, становятся очень редки.

Конечно, причины для изучения и использования jQuery ещё остаются, но если стоит выбор между JavaScript и jQuery, то быстрое развитие технологий JavaScript и некоторые его новые возможности полностью исключают потребность в jQuery.

Причины Различий

Если вы изучаете JavaScript, то ваши возможности в веб-разработке будут гораздо более обширными, нежели использование ограниченного количества кода jQuery. Возможно, добавление готового кода быстрее и эффективнее, но при этом могут возникнуть другие проблемы.

Поведение кода jQuery может быть именно таким, какое вы от него ожидали, но будет тяжело добиться полного соответствия без соответствующих знаний в JavaScript. И, конечно же, стоит понимать, что jQuery состоит из кода JavaScript, поэтому вам нужно будет овладеть JavaScript, чтобы максимально эффективно использовать команды jQuery.

Фактически, JS это jQuery, но с гораздо большими возможностями.

Настолько Ли Всё Просто?

Хорошо, тогда всё стало более понятно? Различие между парой JavaScript jQuery в том, что jQuery более простой и лёгкий, а JavaScript более мощный и гибкий. Значит надо изучать только JavaScript?

Что же, не совсем так. К сожалению, на этот вопрос нет простого ответа. Изучение и использование того или иного инструмента зависит от множества факторов, вроде карьерных возможностей или потребностей вашего собственного проекта.

Карьерные Возможности

Если вашей целью является стать фронтенд разработчиком, то выбор между JavaScript jQuery будет для вас очевидным: изучайте JavaScript. Возможно, объявление о приёме на работу будет требовать знания jQuery, но опытные специалисты по JavaScript всегда будут в приоритете, так как обладают более гибкими возможностями при работе с кодом.

Даже если компания постоянно использует в своих проектах jQuery, после изучения JavaScript освоить jQuery будет гораздо проще и быстрее, чем наоборот. Изучить JavaScript гораздо сложнее, даже если вы мастер в jQuery.

Если вашей целью является стать фриланс веб-дизайнером, то JavaScript вряд-ли будет для вас обязательным условием. Если вы создаёте сайты для клиентов на базе систем управления контентом, вроде WordPress, то большая часть необходимых потребностей в интерактивности будет удовлетворена использованием jQuery.

Кроме того, большая часть сайтов может быть создана без необходимости в пользовательском коде JavaScript. Поэтому пока вы понимаете какой функционал для сайта требует особого кода JavaScript, вы можете обойтись лишь знаниями HTML, CSS и jQuery.

Итак, мы ответили на несколько важных вопросов: что такое jQuery и почему JS это необходимость для разработчика. Кроме того, мы даже узнали о различиях и сценариях для выбора того или иного инструмента.

Поэтому, если вы приняли решение и хотите начать обучение, то можете выбрать один курсов представленных ниже. Но, если вы хотите увидеть более детальное сравнение – продолжите чтение.

jQueryJavaScript

Особый Функционал

Итак, давайте постараемся копнуть немного глубже и взглянем на конкретные ситуации для применения.

JavaScript делает всё, что может делать jQuery, но в каких конкретных случаях лучше использовать код jQuery?

Кросс-Браузерная Совместимость

Если вы упомяните Internet Explorer при разработчике, который уже очень давно занимается разработкой, то можете заметить насколько сильно измениться выражение его лица. Он вспомнит те темныё времена, когда большая часть людей использовала этот знаменитый браузер от Microsoft.

Своему росту jQuery в основном обязан именно тому факту, что ему удалось стереть границу между различными браузерами. Большинство современных браузеров интерпретируют JavaScript похожим образом, но десять лет назад между браузерами были огромные расхождения. Существовала необходимость в написании кода различными способами, чтобы каждый из браузеров правильно его воспринимал.

Или, вы могли просто использовать jQuery, который бы делал эту сложную работу за вас. Библиотека jQuery могла интерпретировать одну строчку кода в определённый код для каждого из браузеров. На тот момент для разработчиков использование jQuery было необходимостью.

Однако в наше время различия между браузерами стали гораздо менее заметными. И если вы обнаружите несоответствия, например, при использовании некоторых функций последнего обновления языка JavaScript ES6, вместо этого рекомендуется использовать полифил. Полифилы — это обычные библиотеки, которые необходимы для устранения различий между браузерами и имеющие возможность реализации с помощью одного URL, который ссылается на соответствующий CDN в теге сценария.

Современные полифилы могут определить браузер, который использует пользователь и предоставить подходящий для этого браузера код. Это экономит много времени, так как пользователю надо будет загрузить лишь одну версию кода, вместо целой библиотеки jQuery.

JavaScript и jQuery - Полифилл

Кросс-браузерная совместимость когда-то была ключевой причиной использования jQuery, но теперь это даже не лучшее решение проблемы, которая сейчас стоит не так остро как когда-то.

Управление DOM

DOM или объектная модель документа является своего рода интерпретацией веб-страницы браузером, которую вы предоставляете. Если вы нажмёте правой кнопкой мыши в любой части страницы и выберите просмотр кода, то под панелью элементов вы увидите DOM. Он может выглядеть как обычный код index.html, но вам стоит понимать, что большая часть HTML-контента динамически рендериться с сервера с помощью серверного языка вроде PHP.

Элементы DOM также могут отображаться и обрабатываться с помощью JavaScript, что является еще одной областью, в которой jQuery однажды оказался чрезвычайно полезным.

С jQuery вы можете направлять ноды DOM, в основном элементы HTML, (вроде заголовков) в коде

З атем вы можете связать функцию с этим кодом и делать все, что захотите, например, прослушивать события или изменять DOM, чтобы менять что-то на вашем сайте, пока пользователь его использует.

С помощью JavaScript вы можете сделать то же самое, используя данный код:

Это не такое большое различие, не так ли? В прошлом методы управления DOM с JavaScript между различными браузерами были не такими простыми. Помимо этого, использование ванильного JavaScript (имеется в виду JavaScript без каких-либо библиотек) считается более эффективным в плане производительности – это означает, что код выполняется быстрее и использует меньше ресурсов памяти.

Опять же, при сравнении JavaScript и jQuery именно JavaScript здесь кажется победителем. Тем не менее, популярность jQuery означает то, что вы обязательно встретите его в различных приложениях.

Новые библиотеки, вроде Bling.js, даже позволяют использовать синтаксис jQuery без необходимости загружать всю библиотеку jQuery целиком, что говорит о сильной приверженности некоторых разработчиков к jQuery.

Кроме того, многие разработчики используют jQuery в тех случаях, когда понимают, что сильной разницы в производительности между использованием ванильного JavaScript и библиотеки не будет.

Поэтому, даже если изучать управление DOM с помощью JavaScript более правильно, знания jQuery в этой сфере всё равно могут вам пригодиться, так как в каких-то моментах это позволит вам сэкономить время.

Эффекты и Анимация

Библиотека jQuery включает в себя огромную коллекцию эффектов, вроде метода toggle, пример кода которого мы представляли ранее. Метод toggle является хорошим примером того, как можно добиться той же функциональности более простым способом.

Хотя на сегодняшний день разработчики имеют доступ к Web Animations API и переходам CSS. Эти две технологии ваш веб-браузер понимает без необходимости в загрузке каких-либо библиотек, что это гораздо быстрее чем загрузка анимаций из библиотеки jQuery.

Конечно, jQuery может быть более простым способом реализации анимации в некоторых случаях, но сейчас для разработчиков существует множество других вариантов на выбор

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *