Beginning the Client Side Hook

Today we worked on creating the client side JavaScript code that would be inserted into every article Engineering.com’s readers would read. They already use a similar style of injecting JavaScript for what they need with every response, so we would simply be adding another hook. This code would use AJAX to send POST requests to our back end API that we’ve now finished creating and testing.

When you want to use AJAX to send HTTP requests, you have one obvious choice, which is jQuery. There’s a lot of documentation on using jQuery for AJAX, and it’s reliable. However, we wanted to minimize the amount of JavaScript that we would be injecting in our hook, so we used a library called axios. This library got us down to about less than 20 kb of JavaScript code going to the reader when they load an article. Its syntax for making the requests is pretty similar to jQuery’s, so learning how to use it isn’t hard.

Creating our client side hook basically involves brainstorming to find out as much information we can capture as possible. For example, we’re going to use the “onscroll” event of the DOM to detect when the visitor has scrolled to the bottom of the web page, because we want to know what articles visitors are interested in enough to finish reading. Some pseudocode for what we created to do this would be:

domElement.addListener(‘onScroll’, function => {
if (/* the user reached the bottom of the page */) {
axios.sendReachedBottomAction(hitId);
// hitId is the client side hook knowing what “Hit” produced this action
}
}

For some things we want to track, like when a visitor closes the web page/tab/browser/loses power/etc… We need something reliable. We can’t rely on an AJAX query finishing firing as the page closes, and we can’t block them with synchronous JavaScript. We believe our solution to this is web sockets, likely using the socket.io JavaScript library. Summarized, web sockets allow you to maintain a persistent full duplex connection between a web server and a client after starting an HTTP request. There’s no need for polling, it’s very quick, and very low overhead. We can use this to continuously check if the visitor is still “alive”. (We will poll, which is technically an anti pattern of web sockets, but we need to do this and the low overhead makes this happen for us).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s