Connect With Us

DesignRush Go to Design Rush

Refactoring JavaScript : Managing existing JS Code

By Shiva Bhusal on Apr, 06, 2016

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. 

Share This:

Latest Posts


Why we organize all hands Annual Retreat? By Promising Software Engineer on Sep, 17, 2019

Career Conclave 2019 By Promising Software Engineer on Jul, 30, 2019

Ruby Workshop at Jyaasa By Promising Software Engineer on Jul, 30, 2019

Bootcamp @ Jyaasa By Promising Software Engineer on Jul, 30, 2019

Integrating Afterpay Payment in a Rails Project By Umesh P Kafle on Sep, 07, 2018