JavaScript require / import / include modules

Require, import or include, name it as you wish but never forget the importance of modular design. This functionality enables you to divide your code into meaningful, purposeful and reusable modules enabling you to use your code as many times as you want and easing it’s maintenance. This functionality is supported in almost all modern programming languages like: C/C++, Java, C#, PHP, Ruby, Python, etc. under different names stated above, but not in only (for now) web client side programming language JavaScript. Of course we can be clever and use trick to emulate this behavior. Flexibility of this dynamic functional language, characteristic that makes it very favorable, will aid us once again to develop similar behavior like any other more complex languages.

Lets say that we have file structure like this:

  • script.js
  • ivar
    • util
      • array.js
      • string.js
    • net
      • _all.js
      • JSON.js
      • REST.js
      • XML.js

In short all we want is to in script.js do this:

require('ivar.util.string');
require('ivar.net.*');
require('ivar/util/array.js');
require('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');

ready(function(){
//do something when required scripts are loaded
});

We also want to include only script.js in our HTML file. To require other scripts, we have to know their names and their locations. To find the root location we have to find the URL of script.js. We will remember it as the root url and then use the supplied namespaces, for example ‘ivar.util.string‘ and transform them into ‘<url of script.js>/ivar/util/string.js‘. Now we have to append to html head dom element scripts with given locations. We will put a loading stack so scripts can be loaded asynchronously. Before loading a script we have to check is the script currently loading or is it already loaded. When all of the required scripts are loaded we will fire the functions stacked with ready method. If we want to include all of the scripts in a directory, we have to have _all.js that requires all scripts in that directory. By requiring ‘ivar.net.*‘ we really require ‘ivar.net._all.js’, that requires all scripts required inside it.

The following code does the described job:

I chose to name the method ‘require’ but you can rename it however you like, remember import is a reserved word for future use in JavaScript, that means at some point module import will be enabled by standard, but until then we have to fallback to methods similar as one stated above. As we can see there is no special philosophy with importing / requiring / including modules in JavaScript. Combining this require module with namespace method described here provides the ultimate system for JavaScript modular development.

I have excluded this code from a large library I am writing so if you find an error or a typo please notify me, I would be grateful. Any suggestions, similar snippets  or any other kind of feedback is welcome in the comments section. I only hope that this peace of code helped you in some way. Thank you.

About these ads

8 comments

  1. Thanks for your grate article.
    I prefer to Minify all my js files into a single file when I am in production environment of a project, but while developing I just include all js files in my header which is really ugly.
    Now I can use your include module and create a file called Terminal.js and that file include Others.

    1. Hey, I’m really glad it was of some use. :D
      I updated the code to be a bit more flexible. Now you can do require(‘other_script.js’) the script that is in the same level as your basic script that is used for location detection. And you can require(‘some_script’, true); Put true if you want the script to be required asynchronously, otherwise it is required synchronously which means that scripts are included by order you required them.
      Heh, maybe it’s not some explanation, i will rewrite the post to describe the abilities of the module.
      Also I will include a small python script that combines the required scripts, all you need to do is minify them later.

      Take care dude! And if you find a bug, please let me know! :)

  2. Hi everyone, it’s my first visit at this web site, and article is genuinely fruitful in favor of me, keep up posting these posts.

  3. […] I wrote a simple module that automates the job of importing/including module scripts in JavaScript. For detailed explanation of the code, refer to the blog post JavaScript require / import / include modules. […]

  4. […] I wrote a simple module that automates the job of importing/including module scripts in JavaScript. For detailed explanation of the code, refer to the blog post JavaScript require / import / include modules. […]

  5. […] I wrote a simple module that automates the job of importing/including module scripts in JavaScript. For detailed explanation of the code, refer to the blog post JavaScript require / import / include modules. […]

  6. First, thank you for this great piece of code that’s really meaningful for client-side apps. But i have a question: does this script-loader you gave us need to be included in the HTML file anyway ? How could i avoid doing that ?

    1. Thank you friend for showing the interest for this simple code!
      Well it has to be included in HTML in order to work, it is used only for developing the application, when you deploy the application you should remove this code and compile all of the codes with let’s say closure compiler. I will maybe write a simple python script to do just that, generate the HTML header based on the imports.
      I’m not sure I understood well, so my response is based on my understanding of your question.
      If you have any other questions feel free to ask! :)

      Peace bro!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 79 other followers

%d bloggers like this: