0

I have a external js file called main.js which is added in the index page. In some cases that main.js can be included from the another sub page, so it is leading to the execution of main.js twice. my main.js structure main.js

 (function() {
 console.log("js execution started");
//content goes here
//
//
}());

how can i avoid the execution of the main.js twice?

2 Answers 2

2

set a global variable, and check if its already set, e.g:

var main;
main=main||(function() {
 console.log("js execution started");
 //content goes here
 return 1;
}());

That also gives you the abillity to make an API available via main.

Sign up to request clarification or add additional context in comments.

Comments

1

Try to add a flag to your window (or your global scope) that shows that main.js is already loaded:

(function() {
  if (window.__MAIN_INSTALLED) {
    return
  }

  window.__MAIN_INSTALLED = true
  console.log("js execution started");
}());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.