How to ensure that duplicate JavaScript doesn’t run twice?

This often happens when your customers are using more than one plugin/addons both requiring the same JavaScript. You can avoid the execution of both of them by using the following trick.

if(window.MyCustomNameSpace === true){
return false;
}
window.MyCustomNameSpace = true

Why it works?

The idea here is to set a namespace as soon as you have tested for its existence. Since you are using ‘window‘ object, it will be globally accessible in all of your JavaScript files.

Complete Template

(function(){
  if(window.MyCustomNameSpace === true){
    return false;
  }
  window.MyCustomNameSpace = true
  
  // Your codes here!

})();

3 Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>