DEV Community

Cover image for Using jQuery in 2019
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

Using jQuery in 2019

Written by Anjolaoluwa Adebayo-Oyetoro✏️

Introduction

There have been discussions on how jQuery, a popular JavaScript library, is dead/dying.

With the rise of modern libraries, frameworks, the standardization of browser APIs, and the decline of job postings that require jQuery skills there is a concern around developers continuing to learn jQuery.

In this post, I will give a run through of jQuery, its history, strengths, weaknesses, why you might still want to use it, and how to get started in 2019.

What is jQuery?

According to jQuery’s official documentation:

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.

Basically, it is a JavaScript library that was built to make DOM manipulations possible at a time when accessing the DOM and doing certain things with JavaScript were practically impossible in older browsers. It made it easier and simpler to write JavaScript and HTML.

The library’s popularity increased when Microsoft and Nokia announced their public support for it in September 2008 and it has maintained at the top in terms of JavaScript library and framework interests within developers until recently, when it has seen many notable companies and libraries that used jQuery as a dependency (GitHub, Bootstrap 5) drop support for it. This has caused a sharp decline in usage and many questions asked on popular platforms like Reddit and StackOverflow.

You can learn more about the history and legacy of jQuery here.

LogRocket Free Trial Banner

What does jQuery offer?

  • Traversing the DOM – jQuery made it easier to traverse the DOM (as there was no standard way to do so). Traversing the DOM in older browsers was a complex thing to do.
  • Manipulating the DOM elements – jQuery makes it easier to change styles and behaviors of elements by using a selector to reference the target element and including a method that applies the changes desired.
  • Animating elements – Animating web content was one of the major selling points of jQuery.
  • Make better HTTP requests – jQuery’s AJAX method to easily handle HTTP requests made earned it many fans as the old way of making an HTTP request in JavaScript – using XMLHttpRequest (XHR) – was a tedious process.
  • A solution to cross-browser compatibility issues – jQuery’s main selling point is its solution to cross-browser compatibility issues. Old browsers did things quite differently as there was no standard way to do things and developers had to make several checks to ensure that JavaScript behaved as needed in IE, Firefox, Opera, Safari and Chrome. jQuery’s introduction ensured web pages were rendered correctly regardless of the browser a user has.
  • Extensive documentation — jQuery’s documentation, resources, and its ecosystem can help developers level-up from newbies to experts very quickly. jQuery is open source (anyone can contribute to or modify it or suggest newer features) and it also has a very large user community on the internet.

Why do developers still use jQuery?

It has several nice features that people find helpful.

Some of them include:

  • jQuery has an extensible plugin system — jQuery has a plug and play plugin system. There are plugins for virtually everything you can think of while building a website or web app from drop-down menus to navigation systems, image uploaders, and carousel sliders. All you need do is download the plugin and use or customize to fit your needs where it is needed.
  • “Write less, do more“ — as stated in its tagline, With jQuery you get more done with fewer lines of code. All sorts of complex actions are done with ease and it encourages writing modular code.
  • jQuery offers simplicity — jQuery doesn’t need any prerequisites to learn. It has a low learning curve and is relatively easier for anyone to pick up and become an expert at it in a very short time. It meets the needs of both developers and designers as it reduces build time considerably.
  • Cross-browser compatibility — jQuery supports older browsers which do not do well with modern tools, frameworks or libraries. jQuery-powered applications work well on all browsers.
  • jQuery is stable — it is stable because there is a dedicated team of lifelong contributors who have volunteered to keep the tool at its best in addition to its large ecosystem.

Developers’ beef with jQuery

Using jQuery comes with its cost. Some of the reasons why developer interests in jQuery waned are:

  • Rendering performance — jQuery sacrifices performance to be able to do a whole lot of other awesome stuff. It makes sites slower as it constantly has to reach for the DOM directly and load a whole library before processing our code which often times lead to jank. The slow performances are barely noticeable in a basic or normal website and might be a perfect trade-off for more features, but in a large complex site where every millisecond counts, jQuery often reduces the performance of such sites.
  • The relative ease of use – One of jQuery’s downfall is the fact that it is very easy to write spaghetti code in it. Due to its relative ease of use, incorrect usage of jQuery’s selector chain, use of non-descriptive variable names and trying to write complex functions, jQuery can lead to writing code that would eventually be unmaintainable.
  • Increased bundle size — with a size of 86.1 Kb or 28kb when gzipped, jQuery adds a bit more size to your website even when most times just a few functions from its library are needed.
  • Modern browsers and evolving web trends — A considerable amount of the cross-browser compatibility issues jQuery solved and the standardization issue that made it so have now been resolved, as improvements are being made to web browsers. Most notably the introduction of ECMAScript 2015 also known as ES6 (the spec that JavaScript follows), creation of new frameworks and specialized libraries that have all made jQuery rather obsolete.

Is jQuery dead?

According to BuiltWith, a web technology statistics aggregator, jQuery powers over 79% of the top 1 million websites in the world and it takes a huge 65% of the JavaScript library usage.

One reason it is still as popular is that many projects still depend on it (Example: Bootstrap 4.0 and below, the majority of the WordPress plugins and themes are built using jQuery) and there are also legacy code-bases that depend on jQuery.

Modern alternatives to jQuery functions

Below are some of the suitable alternatives to popular functions of jQuery.

DOM Selection

To select something in jQuery we would normally do something like:

// The selector name can be replaced with either an ID, a Class name or tag name
$("selectorName")  //  #selectorName or .selectorName
Enter fullscreen mode Exit fullscreen mode

This can be achieved in using the HTML5 DOM API with either:

document.querySelector("selectorName") //gets a single item
Enter fullscreen mode Exit fullscreen mode

or

document.querySelectorAll("selectorName") //gets a group of items
Enter fullscreen mode Exit fullscreen mode

DOM Manipulation

.append() method to insert the content between parentheses to the end of the element(s) specified by a selector.

$("selectorName").append( "Your content goes here")
Enter fullscreen mode Exit fullscreen mode

Its vanilla equivalent can be done like:

let element = document.querySelector('selectorName');
let text = document.createTextNode("your content");
element.appendChild(text);
Enter fullscreen mode Exit fullscreen mode

.addClass() method to add the specified class(es) to each element in the set of elements which are specified by the selector.

$('selectorName').addClass('className');
Enter fullscreen mode Exit fullscreen mode

Its vanilla equivalent:

let element = document.querySelector("selectorName");
element.classList.add('className')
Enter fullscreen mode Exit fullscreen mode

Events

Listening for click events:

$('selectorName').on('click',function(e) {
    //do something
});
Enter fullscreen mode Exit fullscreen mode

Its vanilla equivalent:

let clickedMe = document.querySelector('button');

clickedMe.addEventListener('click', (e) => {
    //do something
})
Enter fullscreen mode Exit fullscreen mode

HTTP requests

jQuery Ajax HTTP requests are made like this:

$.ajax({
  url: 'http://example.com/movies.json',
  type: 'GET'
  success: (response) => {
    console.log(response)
  }
  error: (errors) => {
    console.log(error)
  }
})
Enter fullscreen mode Exit fullscreen mode

This can be replaced with using the JavaScript fetch API that lets you make asynchronous requests. It returns data as a “Promise”.

Fetch

fetch('http://example.com/movies.json',
          {method: 'GET',
          headers: {'Content-Type': 'application/json'},
          }){
        .then(response => response.json())
        .catch(error => console.log(error))
    }
Enter fullscreen mode Exit fullscreen mode

While Fetch is better than AJAX, they are different because Fetch uses promises and the promise returned wouldn’t reject on HTTP status error. Fetch also won’t send or receive cookies from the server.

HTTP requests can also be implemented using a specialized library like axios.

Axios is a promise based open source library for making HTTP requests.

To use axios you can either install it via npm:

npm install axios --save-dev
Enter fullscreen mode Exit fullscreen mode

Then you would import it in your file like this:

import axios from 'axios'
Enter fullscreen mode Exit fullscreen mode

or

you can include axios using CDN.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Implementation

axios({
  method: 'get',
  url: 'http://example.com/movies.json',
  responseType: 'json'
})
  .then(function (response) {
  });
Enter fullscreen mode Exit fullscreen mode

Browser support and cross-compatibility

To get your app or website supported across browsers and to work on older browsers, one can use transformation tools such as Babel that convert (transpiles) ES6 code to browser-compatible code that can be understood across browsers with the help of polyfills for specific features alongside other tools such as Autoprefixer, PostCSS, etc.

Animation

Animations in jQuery are implemented via the .animate method.

$(selectorName).animate(
    {parameters},
    speed,
    callback
);
Enter fullscreen mode Exit fullscreen mode

Animating content on your website can be achieved by using CSS animations.

An important CSS tool for animating content is @keyframes which is used to define the styles to be applied at stages and the animation property or its sub-properties which is bound to a selector, It specifies how to apply the keyframes styles and when to apply them.

p{
    animation-name: animated;
    animation-duration: ;  
}

@keyframes animated{
    0% {
    opacity: 0;
  }        

  50% { 
    opacity: 1;
  }
  100%  {
    opacity: 0;
  }
}
Enter fullscreen mode Exit fullscreen mode


Animations can also be achieved using libraries such as animate.css.

How jQuery compares to modern front-end libraries and frameworks

One of the major reasons jQuery has seen less usage is the rise of JavaScript libraries and frameworks such as React JS, Angular JS and Vue JS, in this section we will look at what sets them apart.

jQuery React JS Angular JS Vue JS
Type Library UI library Full-featured framework Scales between a library and a full-featured framework.
Architecture Modular A component-based library that handles only the View of your app Full-fledged component-based MVC framework Component-based, focuses on the ViewModel layer of the MVVM pattern
DOM interactions Updates the DOM directly Uses a virtual DOM that interfaces with the real DOM Updates the DOM directly Uses a virtual DOM that interfaces with the real DOM
Data binding Databinding methods
with plugins to achieve 2-way dataflow
One way data-flow Two-way data binding can be achieved with ngModel Reactive data binding system

Two-way data can be achieved with V-model

State management Can be achieved using specialized libraries Context API, Redux Third-party libraries such as NGRX, NGXS, etc Vuex
Templating JavaScript JavaScript (JSX) TypeScript and Angular directives HTML, CSS, JavaScript and Vue directives
Learning curve Low Low but strong knowledge of JavaScript is needed High Low all one needs is basic knowledge of JavaScript to get started

Why you might still want to use jQuery in 2019

  • When prototyping products – since jQuery helps to prototype rapidly and get new features done in no time, you do not need to have an in-depth knowledge of it to get things done. With the documentation, one can get a working prototype up in no time.
  • Animating content via vanilla methods is still relatively difficult. jQuery might be a suitable option if your project requires lots of animation as there are tons of customizable plugins that would help compliment the easy to use .animate method.
  • Building for several browsers. If you’re building a website or web app that should work on several browsers seamlessly, jQuery might be the best for your needs. It supports all modern browsers and does a better job at solving cross-compatibility issues, It also solves problems with older browsers such as IE6.
  • To bootstrap small projects and simple sites that do not need a framework.
  • While working with legacy codebases that are built with jQuery.

How to get started with jQuery in 2019

To use jQuery in your project there are a couple of methods to get started.

The latest version at the time of writing this article is version 3.4.1 download the compressed, production version or the uncompressed, development version.

You can include it in your project like this:

<script type="text/javascript" src="js/jquery-3.4.1.js"> </script>
Enter fullscreen mode Exit fullscreen mode

As an alternative, you can use package managers :

npm install jquery
or
yarn add jquery
Enter fullscreen mode Exit fullscreen mode

and import it like this:

import * as jQuery from 'jquery';
Enter fullscreen mode Exit fullscreen mode

Or use the CDN version by including either of the following in your project :

Google CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Microsoft CDN

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.js"> </script>
Enter fullscreen mode Exit fullscreen mode

Conclusion

While modern trends show a shift with developers moving from jQuery to newer libraries and frameworks, the library is still very much alive and actively used, as it has functions that are relatively easier to implement than vanilla methods.

The low skill-demand rate also suggests that one might be better off using newer libraries/framework as there are more job opportunities.

I would advise knowing jQuery and how to implement basic things in it (added knowledge wouldn’t hurt) should there be a need to use it in a project. The documentation provides an excellent resource to get started with.


Editor's note: Seeing something wrong with this post? You can find the correct version here.

Plug: LogRocket, a DVR for web apps

 
LogRocket Dashboard Free Trial Banner
 
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
Try it for free.


The post Using jQuery in 2019 appeared first on LogRocket Blog.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.