Last Updated: February 25, 2016
·
505
· emi420

Another way to work with several files in JavaScript

Let's make a simple loader for organize our code .

For example, you can split a catalog app in 3 views:

  • views/index
  • views/catalog
  • views/product

Have pairs of .js and .html files for each view.

  • views/index/index.js
  • views/index/index.html
  • views/catalog/catalog.js
  • views/catalog/catalog.html
  • views/product/product.js
  • views/product/product.html

And then use a function to include each module:

var include = function(module, callback) {

   var d = document,
         js = module + ".js",
         html = module + ".html",

   loadJS = function(htmlResponse) {
       $.ajax({
            url: "views/" + js,
            success: function(response) {
                var script = d.createElement("script");
                    script.innerHTML = response;
                    d.head.appendChild(script);
                if (typeof callback === "function") {
                    callback(htmlResponse);
                }                
            }
       });
   };

   $.ajax({
        url: "views/" + html,
        success: loadJS
   });

};

include(index, function(html) { 
     $("#main").html(html);
});

For a more advanced approach, use RequiereJS (http://requirejs.org/).