Search Engine Refactor - jQuery to Vanilla JS

Daily Standup

Today I added the ability to search to the project I’ve been working on. I had a good starting point from when I added search to this blog, but I didn’t want to introduce jQuery into that project, so I had to rewrite some sections. In the end I also refactored it a bit to be much clearer to read.

jQuery to Vanilla JS

The biggest change was handling the AJAX requests (loading JSON data) using XMLHTTPRequest instead of $.getJSON(). I considered using the Fetch API or Axios (based on my recent exploration of AJAX methods); but since fetch isn’t supported in IE, and since I really am trying to avoid outside dependencies as much as possible, I went for the simplest option.

Not surprisingly, removing jQuery made the code a lot longer. But that prompted me to break it down into smaller functions to make it more readable. I also think I did a good job improving the function names—I was able to take out most of the comments and it’s still very understandable.

I also made the AJAX call a higher order function since it gets called multiple times:

function getJSON(callback, input) {
var request = new XMLHttpRequest();
request.open("GET", "/content.json", true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
callback(data, input);
}
};
request.send();
};

So nice to see I am learning & improving!

Up Next

I’ve got all the data showing up as it should, and now need to style it and then incorporate search into the nav and footer.