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

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!

})();

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

One thought on “How to ensure that duplicate JavaScript doesn’t run twice?

Leave a Reply to Norris Cancel reply

Your email address will not be published. Required fields are marked *

Scroll to top