javascriptjqueryajaxevent-listeneronreadystatechange

EventListeners, onreadystatechange, or jQuery for AJAX calls?


I'm making calls to the OpenWeatherMap API to get a weather forecast JSON object. I used 3 different javascript methods that are called when someone enters a zipcode in the zipweather html id element and presses submit or enter, calling zipWeather() and basically pasting the zipcode to the end of the api address which then sends back the data on that zipcode.

They all work fine. They all get a city name and temperature that is converted into Fahrenheit.

They all use a callback in the error handler to the function itself in case of failure. The first one uses a 5 second timeout callback.

onreadystatechange method:

function zipWeather() {
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
//responseText code
}
// else ifs for readystate 3 2 and 1 gives a console log
else {
console.log("request failed, retrying in 5 seconds...");
window.setTimeout(zipWeather, 5000);
return;
}
}
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + document.getElementById("zipweather").value,
true);

xhr.send();

event listeners instead of onreadystatechange:

xhr.addEventListener("load", function() {
//responseText code
}, false)

xhr.addEventListener("error", function(err) {
console.log(err);
if (weatherData.retryCount <= weatherData.retryMax) {
    weatherData.retryCount++;
    console.log(weatherData.retryCount);
    console.log(err);
    zipWeather();
    return;
    }
else {
return;
}

and of course jquery:

function zipWeather() {
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + $("#zipweather").val(),
data: {},
dataType: 'json',
success: function(data) {
console.log(data.name);
$('#weather').html(data.name).css({'color': 'blue', 'text-shadow': '1px 0.5px lightblue'});
//change from kelvin
var localTempF = Math.round((data.main.temp - 273.15) * 9/5 + 32);
$('#localtemp').html(localTempF + weatherData.localUnits);
weatherData.localTemperatureValue = localTempF;
},
timeout: 3000,
retryCount: 0,
retryMax: 5,
error: function(jqXHR, textStatus, errorThrown) { 
this.retryCount++;
    if (this.retryCount <= this.retryMax) {
    //try again
    $.ajax(this);
    return;
    }
return;
}

The last two methods use a retryCount and retryMax variable trick I found in What's the best way to retry an AJAX request on failure using jQuery? so it doesn't keep calling the API if its down.

Finally, questions:

  1. Are all of these methods virtually identical in terms of performance? Is there a potential catastrophic bug lurking in any method as written?

  2. Is it most proper to use a callback in the error handler to the same function when using AJAX?

  3. Are javascript code standards moving away from using onreadystatechange or event handlers and towards jquery $.ajax and $.get functions?

Thanks everyone. Sorry it was so long!


Solution

  • You can probably answer the performance question yourself with performance testing tools. I prefer event listeners because the code reads more cleanly. Bug-wise, I would categorize the lack of a way for the first method to break out of a callback loop if the service is down as a serious bug. It could cause performance degradation if the service is down, that is something to check with performance testing.

    I don't know whether there is a convention to re-call the method in the error handler, but it seems like an OK way to handle it as long as you have a loop breakout. If the retry max is reached, you might want to alert the user and prompt them that the service call will be attempted again after some arbitrary period. See the way Gmail handles connection interruptions for an example of this behavior.

    As for jQuery v. not jQuery, it depends on your use case. In a lightweight web page where you are performing minimal JavaScript coding, you might find jQuery to be overkill in terms of the size of the library. On the other hand, jQuery is popular because it papers over browser incompatibilities, letting you, the coder, focus on application functionality. If you load it from a popular CDN, many users may already have it in cache, so load time would not be a factor. As for what people use, jQuery is popular, but beyond that I don't know whether any statistics exist that break down the relative popularity of either method.