Чем отличается 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.

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.

Key Differences Between jQuery and JavaScript: An Expert Guide

Alexandre Ouellette, contributor to the CareerFoundry blogby Alexandre Ouellette, UPDATED ON SEPTEMBER 3, 2021 8 mins read

When I first started learning to code, I found it difficult to navigate through the terminology, jargon, and acronyms that seem to accompany every technology I played with.

And it can get even harder when things sound very similar, or operate in a similar ecosystem.

One of my earliest questions was “What is the difference between JavaScript and jQuery?” Are they one and the same, or are they completely independent?

In this article we’re going to demystify that question, and leave you with a better understanding of what both of these technologies are, as well as the benefits of using them. Let’s dive in!

1. What exactly is JavaScript?

Another question novices often find themselves asking is, “So, JavaScript is just like Java, right?” Unfortunately not—there’s no relation between the programming language Java and JavaScript, other than a little bit of syntax and an unfortunate naming choice.

JavaScript was created in the mid-90s, by Brendan Eich while working at a company called Netscape as part of the Netscape Navigator project, an early web browser. The language was standardized in June of 1997, when Ecma International released the first version of its standard, which included JavaScript as one of its implementations.

JavaScript has since then been widely considered as the language of the web. It can be run by all modern web browsers without needing any additional plugins.

It has also exploded in popularity in the past couple of years. It has been used to develop frontend frameworks to help developers create complex web applications, to develop native applications and it has even started to be used server-side, thanks to projects such as Node.js, which makes it a full-stack language. If you’d like to learn more about how that works, then our beginner’s guide to Node.js will explain all.

It’s consistently up at the top of Stack Overflow’s most-wanted languages list. What’s more, our research on JavaScript developer salaries shows that this language is a nice earner, too.

All in all, there seems to be no better time than now to learn JavaScript and I can’t encourage you enough to take a look at it. In this video Abhishek, one of our in-house developers, takes you through the first steps:

2. So what is JQuery then?

JQuery is a library, written in JavaScript, that is used to simplify frontend code that manipulates HTML.

Wow, there was quite a bit of jargon in that definition. Let’s take a minute to define some of it.

A library, like where I get books?

In programming, a library is a collection of useful code, grouped together to be reused later.

Libraries have a well-defined interface that makes it easier to perform the functions it was designed to do. They generally make it so you have to write less code to accomplish the same amount of work.

So let’s say you wanted to write a program, which at some point saves some data to your hard drive. You could write that entire program yourself, which would be quite a bit of work. Or you could use libraries someone already created, to make some parts of that program easier to code.

The code that actually writes the data on your hard drive would be quite complicated to implement, and would require you to know how to work with low level programming. But if someone already figured it out and made that code available, that would be a library you could add to your program so you don’t have to think about it.

Another example of a popular JavaScript library is React.js, which you can learn more about in our React guide.

3. Perfect, now what is frontend code?

Typical web applications can be thought of as having two parts—the backend (server-side) and the frontend. Knowing the difference between the two is essential to being a web developer.

The server-side code is code your users never see. It’s the code that is responsible for the logic of your application, the code that saves data to a database, etc.

The frontend code is your web page and everything that your user sees. It includes the HTML that gives your web page its structure, the CSS that makes that page look great, and the JavaScript, or in our case the JQuery, code that gives it functionality.

4. What does JQuery do exactly?

JQuery makes it easier for you as a developer to interact and modify your HTML and the data it contains. For example, let’s say you want to disable that button so it can’t be clicked again. You could do that with the following JQuery code:

JQuery is used twice in there. The first being the selector, which is represented by the $. This will go through your web page and it will return an HTML element with the i.d. “my-button” if there is one. Then through the use of the .prop method, it will change that element’s properties, to include the “disabled” property with a value of true. And voilà—you can’t click your button anymore.

As you can see, the code above looks just like JavaScript, and that’s because JQuery is written in JavaScript, which makes its syntax really similar. Furthermore, it can be used in any web page that JavaScript can, as long as you include it as part of your webpage’s code.

We could also accomplish the same thing as above with normal JavaScript by writing the following code:

Though the code isn’t that much more complicated for our simple example, I would need a much more complicated explanation to explain what document refers to and why we can use the getElementById function on it.

JQuery’s $ effectively replaces JavaScript’s document.getElementById, so you don’t have to worry about it. Plus, it saves you quite a bit of typing!

Plain JavaScript examples get a lot longer when you try to implement some more complex features, such as event handling or AJAX calls. I recommend you look at JQuery’s documentation to learn more about those advanced use cases and how much work JQuery can really save you.

The JQuery Foundation also has a lot of other libraries to simplify other aspects of front-end development. Such as their JQuery UI library, which allows developers to easily create user interface elements that are commonly used in websites, such as date pickers, menus and popup boxes. These elements require a tremendous amount of work to implement in JavaScript alone.

5. Downsides to JQuery to be aware of

It’s important to note that even though it is one of the most popular JavaScript libraries used on the web today, JQuery does have its limits.

It is very useful in small or medium applications, but large codebases written exclusively with JQuery can get unwieldy, due to its lack of imposed structure.

The newly developed frontend frameworks make it easier to write large, complex frontend applications and are a good alternative to JQuery for large codebases.

6. Where should I go from here?

As you learn to code and work on building your development skills, I highly recommend dedicating quite a bit of your time towards JavaScript.

It has gained so much popularity recently and has evolved into a much more versatile and useful language, which makes it worth learning.

And I would also recommend looking through JQuery’s documentation to see if it can be applied in your next project. I recommend the JQuery UI library, it has saved me quite a bit of work in the past and it will always have a special place in my heart.

If you’re looking to read a bit more on JavaScript and similar languages, have a look at these articles:

What You Should Do Now

Get a hands-on introduction to web development and build your first website from scratch with our free, self-paced Web Development Short Course.

Take part in one of our FREE live online web development events with industry experts , and check out recent graduate Tanimara’s successful career-change story.

Become a qualified web developer in just 5-10 months—complete with a job guarantee.

This month, we’re offering 100 partial scholarships worth up to $1,285 off our career-change programs �� To secure your discount, speak to one of our advisors today!

This article is part of:

Web Development

Alexandre Ouellette, contributor to the CareerFoundry blog

Alexandre Ouellette has been working in the tech industry for around seven years, and right now is working as an IT Technician in Ottawa, Canada. He studied web development with CareerFoundry.

Related Web Development Articles

What is a DevOps Engineer? A Simple 2023 Beginner’s Guide

What is a DevOps Engineer? A Simple 2023 Beginner’s Guide

Why AI Won

Why AI Won’t Replace Web Developers Anytime Soon

The 2023 Complete Computer Programmer Salary Guide

The 2023 Complete Computer Programmer Salary Guide

What is CareerFoundry?

CareerFoundry is an online school for people looking to switch to a rewarding career in tech. Select a program, get paired with an expert mentor and tutor, and become a job-ready designer, developer, or analyst from scratch, or your money back.

Разбираемся в Проблеме Пары 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 не будет опубликован. Обязательные поля помечены *