Should I abandon JQuery?

Should I abandon JQuery?

Preface

I used to love jQuery, and to be honest, I learned jQuery before I learned JavaScript. So I'm kind of betraying jQuery by writing this.

I know there are tons of articles out there about why you shouldn't use jQuery, but I just wanted to share my personal experience.

What to use if not jQuery?

With the development of the web, new technologies are constantly being pushed forward by the new ones, and the old ones die on the beach. Just like some programming languages ​​were once glorious, but now they have disappeared. I think jQuery is no exception. It's time to say goodbye to it, although it once brought us a wonderful programming experience.

Why give up jQuery? Because of Vue! If you have read my previous articles, you should be able to guess that I am a fan of Vue.js. Vue.js provides a lot of tools, and I dare say it is much more convenient than jQuery.

DOM and Events

Let's look at an example of a click event.

Please note that I omitted the initialization of the framework.

A Vue SFC (don’t panic, it means Single File Component):

<template>
    <button @click="handleClick">Click me, push harder</button>
</template>

<script>
    export default {
        methods: {
            handleClick() {
                alert('My friend, you clicked the button');
            }
        }
    }   
</script>

This is how you write it with jQuery:

<button id="myButton">Click it</button>

<script>
    $('button#myButton').click({
        alert('This time using jQuery');
    });
</script>

You might think that Vue.js has more code, and you’re right, but you’re also wrong! Vue.js does not have more code. In fact, the part other than handleClick() { ... } is just the structure of the framework, which is shared with other behaviors. I think Vue.js looks cleaner and the code is more readable.

You may still have a question in your mind, why did you still use Vue.js? Isn’t it the pot calling the kettle black? If you have the ability, don’t use it! You can actually do this with plain JavaScript:

<button id="myButton">Come and click me</button>

<script>
    document.getElementById('myButton').addEventListener('click', function() {
       alert('Greetings from native js'); 
    });
</script>

So you see, jQuery just translates the code into native JavaScript behind our backs, pretending to be special.

As for the selection of DOM elements, it can be easily done with native JavaScript:

document.getElementById('myButton'); // jQuery => $('#myButton');
document.getElementsByClassName('a'); // jQuery => $('.a');
document.querySelectorAll('.parent .a'); // jQuery => $('.parent .a');

AJAX Requests

Perhaps the most common use of jQuery is in AJAX.
We all know that jQuery provides $.ajax(), and we can also use the specific $.post() and $.get() respectively. These APIs can help you send AJAX requests, get results, and more.

There are two methods you can use in native JavaScript, namely XMLHttpRequest and fetch.

XMLHttpRequest is also an old antique and is not quite the same as fetch.

Fetch is newer and more commonly used than XMLHttpRequest, and is promise-based.

Fetch does not send cookies by default, and it will not reject if the HTTP status code returns an error code, such as 404 or 500, so basically .catch() will not run, but response.ok will become false.

I will not compare them in detail here.

Let's look at two more pieces of code.

Here is the jQuery:

$.ajax({
  method: "POST",
  url: "http://localhost/api",
  data: { name: "Adnan", country: "Iran" }
}).done(response => console.log(response))
  .fail(() => console.log('error'));

The sample code comes from the jQuery official documentation

Here is the fetch:

fetch(
    'http://localhost/api',
    {
        method: 'POST'
        body: { name: "Adnan", country: "Iran" }
    }
  ).then(response => console.log(response));

Both pieces of code do the same thing, but fetch does not belong to any library.

Note that fetch can also be used in conjunction with async/await, as shown below:

async function getData() {
    let response = await fetch('http://localhost/api' {
        method: 'POST'
        body: { name: "Adnan", country: "Iran" }
    });
    return response;
}

Do I use fecth myself? Actually no, because I don’t really trust it for a number of reasons. So I'm using a library called axios, which is also promise-based and very reliable.

The above code is written as follows using axios:

axios({
    method: 'POST',
    url: 'http://localhost/api',
    data: { name: "Adnan", country: "Iran" }
}).then(response => console.log(response))
  .catch(err => console.log(err));

Axios can also be used in conjunction with async/await:

async function getData() {
    let response = await axios.post('http://localhost/api' {
        name: "Adnan",
        country: "Iran"
    });
    return response;
}

Summarize

I don't use jQuery anymore, although I used to love it and the first thing I did after initializing a project was to install jQuery.

I believe we no longer need jQuery because other libraries and frameworks can actually accomplish tasks more conveniently and more concisely than jQuery.

There may be a large number of plug-ins based on jQuery, but basically there are corresponding Vue.js or React.js component alternatives.

The above is the details of whether to abandon JQuery or not. For more information about JQuery, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to introduce and use jQuery in Vue
  • Two ways to make Vue implement jQuery calls
  • Will jQuery die? Why don't I use Vue to write rich text
  • Detailed comparison between jQuery and Vue
  • Introduction of JQuery-ui plug-in in Vue project
  • Steps to use the Jquery-contextmenu plugin in a Vue project
  • Example of multi-select drop-down list function implemented by jQuery+vue.js
  • vue-cli introduces jQuery, Bootstrap, and popper
  • In-depth analysis of the differences between angular, vue and jquery
  • Vue introduces jQuery to achieve smooth scrolling to the specified position

<<:  A solution to the abnormal exit of Tomcat caused by semaphore

>>:  How to fix abnormal startup of mysql5.7.21

Recommend

CSS realizes the layout method of fixed left and adaptive right

1. Floating layout 1. Let the fixed width div flo...

Example code for implementing fullpage.js full-screen scrolling effect with CSS

When I was studying CSS recently, I found that I ...

Solve the problem after adding --subnet to Docker network Create

After adding –subnet to Docker network Create, us...

MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...

Implementation of react automatic construction routing

Table of contents sequence 1. Centralized routing...

JS practical object-oriented snake game example

Table of contents think 1. Greedy Snake Effect Pi...

Getting started with JavaScript basics

Table of contents 1. Where to write JavaScript 2....

Solution to data duplication when using limit+order by in MySql paging

Table of contents summary Problem Description Ana...

JS removeAttribute() method to delete an attribute of an element

In JavaScript, use the removeAttribute() method o...

In-depth analysis of the Tomcat server of Centos 7 system

Table of contents 1. The origin of tomcat 1. Tomc...

Explanation and example usage of 4 custom instructions in Vue

Four practical vue custom instructions 1. v-drag ...

Solve the problem of docker container exiting immediately after starting

Recently I was looking at how Docker allows conta...

Implementation of deploying Apollo configuration center using docker in CentOS7

Apollo open source address: https://github.com/ct...

Vue uses OSS to upload pictures or attachments

Use OSS to upload pictures or attachments in vue ...

Detailed analysis of the blocking problem of js and css

Table of contents DOMContentLoaded and load What ...