Note that there are some explanatory texts on larger screens.

plurals
  1. POApproaches to modular client-side Javascript without namespace pollution
    text
    copied!<p>I'm writing client-side code and would like to write multiple, modular JS files that can interact while preventing global namespace pollution. </p> <p>index.html</p> <pre><code>&lt;script src="util.js"&gt;&lt;/script&gt; &lt;script src="index.js"&gt;&lt;/script&gt; </code></pre> <p>util.js</p> <pre><code>(function() { var helper() { // Performs some useful utility operation } }); </code></pre> <p>index.js</p> <pre><code>(function () { console.log("Loaded index.js script"); helper(); console.log("Done with execution."); }) </code></pre> <p>This code nicely keeps utility functions in a separate file and does not pollute the global namespace. However, the helper utility function will not be executed because 'helper' exists inside a separate anonymous function namespace. </p> <p>One alternative approach involves placing all JS code inside one file or using a single variable in the global namespace like so:</p> <pre><code>var util_ns = { helper: function() { // Performs some useful utility operation. }, etc. } </code></pre> <p>Both these approaches have cons in terms of modularity and clean namespacing.</p> <p>I'm used to working (server-side) in Node.js land where I can 'require' one Javascript file inside another, effectively injecting the util.js bindings into the index.js namespace. </p> <p>I'd like to do something similar here (but client-side) that would allow code to be written in separate modular files while not creating any variables in the global namespace while allowing access to other modules (i.e. like a utility module).</p> <p>Is this doable in a simple way (without libraries, etc)?</p> <p>If not, in the realm of making client-side JS behave more like Node and npm, I'm aware of the existence of requireJS, browserify, AMD, and commonJS standardization attempts. However, I'm not sure of the pros and cons and actual usage of each.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload