Connect With Us

Refactoring JavaScript : Managing existing JS Code

By Shiva Bhusal on Oct, 16, 2016 in js, javascript, ready, refactoring

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:

Comments


Add a new comment

Latest Posts


Design Sprint By Neha Suwal on Aug, 14, 2017

3 years of helping startups and entrepreneurs with technology By Neha Suwal on Aug, 04, 2017

Digital Marketing for Startups By Neha Suwal on Jun, 30, 2017

Jyaasa in Prestige Talks By Neha Suwal on Jun, 16, 2017

Helping digital era entrepreneurs: How Jyaasa helped create a tech startup success story in Sydney. By Kapil Raj Nakhwa on May, 29, 2017