Refactoring javascript : managing existing js code

As an web developer we always have so many problems regarding Javascript as our lines of codes in our app grow. The root cause of these problems are

  • There are so many files. In any of the files you might have missing semicolons, or used undefined variables
  • You often forget to put var before variable declaration, and this put the variable in the global scope
    • This variable might conflict with same variable name you used in other part of your code.

Solution

  $(function () {
    if ($('body.shares').length == 0 && $('body.pact_profile_page').length == 0)  return false;
    ...
  });

  // Basic syntax would be
  $(document).ready(function () {
    var target_element_is_not_loaded = ($('.your-target-selector').length > 0);
    if (target_element_is_not_loaded) return false;
    
    ...
  });

The basic idea is, you only execute your code if your targeted page is loaded. Means if your JS code is meant for posts page then you do not need to load this code else where.

 

Other Links

http://jyaasa.com/blog/refactoring-javascript-managing-existing-js-code

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