Structure your code!

In the past, I've seen many cool project but their management of files were horrible. Whenever you needed a file, you had to search hours to find them. Also, many of them had just one huge file with thousands of lines of code in it. So here's my very easy structure way!

Directory management

I keep my folders always the same way. In the development phase, it looks like this:

-/root
 -/assets
   -image.png
   -image2.png
 -/css
   -framework.css
 -/js
   -/libs
     -framework.js
     -jquery.js
   -/core
     -init.js
     -functions.js
   -/home
     -moreinfo.js
     -imagegallery.js
   -/contact
     -ajaxsend.js
     -formcheck.js
 -/less
  -base.less
  -home.less
  -contact.less
 -index.html
 -contact.html

But after I compiled everything and it's ready for distribution, it looks like this:

-/root
 -/assets
   -image.png
   -image2.png
 -/css
   -style.min.css (compiled less files)
   -framework.min.css
 -/js
   -framework.min.js
   -jquery.min.js
   -scripts.min.js (compiled JS files)
 -index.html
 -contact.html

The code management

Like you have seen above, I don't have one huge JavaScript file where all code gets put in, I have multiple files. To prevent the code getting messy with dozens of functions, I code like this:

init.js:

  1. var defines = { // Important variables that never change
  2. max_animation_time: "1s",
  3. ajax_form_url: "ajax.php"
  4. };
  5.  
  6. var vars = { // Variables that get used everywhere and may change
  7. current_user_id: 4572,
  8. current_user_name: "Joe"
  9. };
  10.  
  11. // Prepare all objects
  12. var home = {};
  13. var contact = {};

The last two objects (home and contact) will be used in the corresponding files, like home/moreinfo.js:

  1. home.moreinfo = function() {
  2. alert("This is a bit more information");
  3. };

They can go even deeper, like in home/imagegallery.js:

  1. home.imagegallery = {}; // prepare object
  2.  
  3. home.imagegallery.init = function(images) {
  4. $(images).each(function(i){
  5. $("#images .container").append("</img>").attr("src", images[i].file);
  6. });
  7. };

Some small tips

These things are also important.

  • Use comments, especially in bigger projects or in team projects
  • Write readable code
  • Don't delete source files (like less files or unminified JS files)
  • Make backups

I think you should be good-to-go now and be able to write nice, organized code!


Code

Newsletter

Subscribe to my newsletter and stay tuned.


Donate

Enjoy this blog? Awesome! If you feel generous, I’d appreciate a small tip. Thanks!

Donate with PayPal