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 ?

  • Why would you need to do that – adeneo May 07 '17 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? – Quentin May 07 '17 at 18:51
  • Possible duplicate of [Can we call the function written in one JavaScript in another JS file?](http://stackoverflow.com/questions/3809862/can-we-call-the-function-written-in-one-javascript-in-another-js-file) – Blue May 07 '17 at 18:53
  • Another possible duplicate: https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file – Blue May 07 '17 at 18:53
  • I am using Scratchpad of Firefox Developer Edition – Achraf Ahmed Belkhiria May 07 '17 at 18:54

2 Answers2

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();
Scarysize
  • 4,131
  • 25
  • 37
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();
quirimmo
  • 9,800
  • 3
  • 30
  • 45