Connect With Us

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


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

Switching to React Native from Ruby on Rails By Kamal Pandey on Aug, 29, 2018

Jyaasa in IT Career Fair 2018 By Sonika Thapa on Jun, 12, 2018

Encrypted secrets in Ruby on Rails By Rasna Shakya on Apr, 20, 2018

Rails Payment Integration with zipPay (Buy Now and Pay Later) By Nelson Suwal on Mar, 23, 2018