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!

})();

Why do you need a self-invoking function in JavaScript?

What is a Self-Invoking function?

A self-invoking function is called immediately after definition. For example look at the following codes:

[code lang="javascript"]
(function(){
    // Called as soon as inserted
    console.log("I am running");
})();
[/code]

Why do you need a self-invoking function?

A self-invoking function is an anonymous function and thus all the variables defined inside it are scoped and hence you keep the namespace polution out of it.

[code lang="javascript"]
(function(){
    var i = 0;
    console.log(i); //prints 0
})();
console.log(i); //prints undefined
[/code]

In JavaScript, scopes are “function-level