re: Hating jQuery will not make you cool VIEW POST

TOP OF THREAD FULL DISCUSSION
re: I completely agree with you that people use it and it is simpler. jQuery take around 30kb and beginners most of the time don't care about this cost...

Actually 5-10 features in 30 kB is not bad at all.

how?

When you can do the same with Vanilla JavaScript by writing little more code.

In 2019 you need not to write very much code compared to jQuery.

Here's an AJAX call in jQuery:

$.ajax({
    url: "/faq/ajax",
    datatype: 'json',
    type: "POST",
    data: {search:'banana'},
    success: (r) => {
        console.log(r['name']);
    }
});

And it's Vanilla JS equivalent:

var r = new XMLHttpRequest();
r.open("POST", "/faq/ajax", true);
r.onreadystatechange = () => {
    if (r.readyState != 4 || r.status != 200) {
        return;
    }
    var a = JSON.parse(r.responseText);
    console.log(a.name);
};
r.send("search=banana");

To me, the jQuery version is clearly simpler and easier to read, with much less boilerplate.

And remember that the Fetch API still isn't fully supported on some browsers, so some people will still prefer AJAX.

Yes, Vanilla JavaScript code is pretty ugly and I completely agree with that but using library just because your code doesn't look pretty is not a good idea at all. It will cost you a lot ( 30 kb).

Remember You can make the code more readable just by breaking it into function.

function ajaxRequest(url, params, callback){
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
            callback(request.responseText); 
        }
    }; 
    request.open('GET', url);
    request.send();

}
    ajaxRequest('https://www.domain.com', null,function(response){
       console.log(response);
    }); 


That was just an example. There could be a bunch of these cases in the code, and besides, 30 kB isn’t all that much anyway.

code of conduct - report abuse