How to use a single jQuery function without importing the whole library?

1

I'm making a Firefox extension and in it I import JQuery everything. In the project I only use the getJSON(); function.

I searched the net and did not find much. I researched the github repositories and found some, but I do not know if they are reliable or if there is a more workable solution.

So I wanted to know if there is any way to just import the function I use instead of the whole library, making my code much better.

    
asked by anonymous 10.03.2017 / 04:59

1 answer

4

The jQuery.getJson() function is an alias for an AJAX HTTP GET call, ie you are only using the ajax() method of the library, so you are only using an asynchronous call and receiving a JSON in response, correct?

To do the same without importing the entire library you can use XMLHttpRequest which is what the jQuery.ajax() (and its jQuery.getJSON() ) method uses, since it is just a wrapper.

While with jQuery you would do

$.ajax('service/user/1234', {
    method: 'POST',
    contentType: 'application/json',
    processData: false,
    data: JSON.stringify({
        name: 'João de Barros',
        age: 34
    })
})
.then(function success(userInfo) {
    // userInfo será um objeto contendo propriedades como nome, idade, 
    // endereço, etc.
});

With XMLHttpRequest you would do so

var xhr = new XMLHttpRequest();
xhr.open('POST', 'service/user/1234');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        var userInfo = JSON.parse(xhr.responseText);
        // userInfo será o mesmo objeto contendo propriedades como nome, 
        // idade, endereço, etc.
    }
};
xhr.send(JSON.stringify({
    name: 'João de Barros',
    age: 34
}));

Ref.:

10.03.2017 / 05:16