Javascript refactoring

Might sound funny.. but ya.. i liked what i did today, so thought of sharing it..

So there was this combo box which needed to be pre-filled with currencies. This list of currencies was also loaded in a javascript array for other reasons.

The immediate refactoring was to use array to create options for the combo box. So i created a function which was called on body OnLoad event which would fill the select html element.

Was this required? This function will be called only once that too only onload of the page. Hmmm.. So my next refactoring was to remove the function and make javascript inline with my html body content.. Solved!

The advantages:

  • The function would make no sense, as in imagine a developer checking this code, he would be confused as to where all this function is used.
  • Debugging is easier. You don’t have to go to head to check your function, rather can just  write the js code where ur html element is.

The disadvantages(as mentioned by Kirit Pamar):

  • The javascript code is sent to the client each time a request is made to that page. This would be the case even if we called a method on body load. You could shove this script in a .js file and call the method on body load. This would improve the page load for each subsequent page request.
Advertisement

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.