Thursday, April 28, 2016

Old JavaScript story


When I first joined Livehelper, back in the days before JQuery, the first problem I was given was this, “Sometimes our scripts don't work. Can you find out why and fix it?”

Livehelper used JavaScript code to track visitors to websites. Our clients were website owners, and
would put our code on their sites, and the script would report back to the servers on how long the users were spending on each page. We also allowed the operators to pull the client into a chat.

I tried asking the customer relationship manager a few questions, such as when does it happen, and if he had any examples of sites where it didn't work, if it was possible that the problem was in the server end. But all he knew was that sometimes, it would work for all clients, but not for that one particular client who had a problem. And we didn't know why, and we had not been able to fix it.

Since I was new to Livehelper, I had to understand the code, and so I started going through it, and writing alerts and making sure that the code worked as expected.

I also started getting to know the team, and they became more comfortable with me. I could ask a few more open ended questions, and eventually, I learnt something that might be useful – whenever the script didn't work, the client website had a lot of JavaScipt on the page.

Earlier, while going through the code, I noticed that we had used global variables like w for width, l for length etc. This was necessary because we had to reduce the size of our scripts and reduce download times. I used a 56 kbps modem at that time.

But I also remembered what I learnt at my first job at Infoyug, that we do not use global variables like “i”. “i” can be used as a local variable inside a for loop, but if you want a global variable, you need it to be very long and descriptive, so that you do not override it by mistake.

And that is what I thought was happening here. The clients were trying to reduce their javascript sizes too, and must have been using the same variables that we were, and if our script was loaded first, it wouldn't work because our variables were being overwritten.

I spoke to the managers about what I thought the problem was, and we agreed to try changing our variables to lhW, lhC etc.

Once we made this change, the scripts started working properly on every site, and we never lost another customer due to our code not working.

No comments: