Search code examples
javascriptiife

Same IIFE, different js files


I have 3 different scripts in a webpage I am building and it all works fine.

However, after I've learned about the advantages of the IIFE, I am trying to wrap all my scripts in one single IIFE but it is not working. An error appears on the console: 'Uncaught SyntaxError: Unexpected end of input' refeering script-1.js.

So, I have something like:

<script type='text/javascript' src='...script-1.js'></script>
<script type='text/javascript' src='..script-2.js'></script>
<script type='text/javascript' src='script-3.js'></script>

And what I am doing is: On script-1.js I started the code like this

(function() {

//....rest of javaScript code script-1

And on script-3.js I ended the code like this:

//....rest of the code script-3

})();

1) Now, the first question is: Is this possible? to wrap different js files in the same IIFE? In theory seems that it is, but I am not sure.

2) Then, if it possible, Am I doing something wrong?

I know that for most of you this seems very basic but I will appreciate some feedback:)


Solution

  • Each individual script must be syntactically complete on its own, you can't have a single IIFE spanning scripts.

    Instead, look at script bundlers/module systems like RequireJS, Webpack, Browserifty, etc. They help you avoid globals while expressing inter-dependencies between your individual scripts, and help with bundling those into a single script for deployment (if desired).