0

Consider the two following files:

// main.js
Somescript();

Call the mod.js here

Somescript();

and

//mod.js
alert('a');

How can I call the file mod.js to run in main.js file ?

5
  • Why would you need to do that Commented May 7, 2017 at 18:51
  • 1
    JavaScript has no built-in mechanism for this. It might be possible depending on the particular JS runtime you are using. What runtime is it? WSH? NodeJS? A browser extension? A script element in a webpage? Something else? Commented May 7, 2017 at 18:51
  • Possible duplicate of Can we call the function written in one JavaScript in another JS file? Commented May 7, 2017 at 18:53
  • Another possible duplicate: stackoverflow.com/questions/950087/… Commented May 7, 2017 at 18:53
  • I am using Scratchpad of Firefox Developer Edition Commented May 7, 2017 at 18:54

2 Answers 2

1

Implement those "files" as modules and bundle them using a module bundler like browserify or webpack.

The simple solution is to make your mod.js module globally available to your main module by adding to the window object:

// mod.js, define
window.myModule = () => alert('a');

// main.js, execute
window.myModule();
Sign up to request clarification or add additional context in comments.

Comments

1

You can:

1) Use a library like require.js to dynamically require JS files.

2) Define your mod.js code wrapped inside a main function. Import inside the page your mod.js before your main.js and inside your main simply call your function defined in the mod.js

<script type="text/javascript" src="mod.js"></script>
<script type="text/javascript" src="main.js"></script>

Your mod.js would be something like

function myFunction() {
  // all the mod.js code I want to execute 
}

Your main.js:

Somescript();

myFunction();

Somescript();

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.