webketje
webketje

Reputation: 11006

Loading one JS file before another

Ok so I have a .js file with about 10k lines of code. This code can be split up in

  1. sub-object definitions
  2. container object definitions
  3. initialization code (after the objects have been defined)
  4. program functionality

I would like to split this one file into 4 separate files, because it provides a better oversight. How do I go about doing this, given that they absolutely have to be declared in that order? What should I wrap up in a $(document).ready() and what not?

If I just separate the files and link them to the html in the correct order, I get undefined object errors. I was also thinking of something like this; but I don't know if that's any good...

Second JS File

function initializeContainers() {
    var containerObj1 = {
      bla: 'bla',
      bla2: 'bla2'
    },
    var containerObj2 = {
      bla: 'bla',
      bla2: 'bla2'
    };
};

First JS File

$(document).ready(function() {
  function initializeSubObjects(callback) {
   var subObj1 = {
     somekey: 'somevalue',
     someke2: 'someothervalue'
   };
  callback();
  };
  initializeSubObjects(initializeContainers);
});

I have no clue whether this is the correct way to do it? PS: I also know you can add the script tags dynamically; but is that good practice?

Upvotes: 1

Views: 1513

Answers (1)

Kenneth
Kenneth

Reputation: 28747

In your example, you should swap the contents of your first and second file. You should only call the initializeContainers method when you know for sure the file has been loaded.

The easiest way to think about this is to load all files with definitions first (helpers, functions, classes, ...). Once all these are loaded, put the rest in the last file and start executing the code only in the last file

On a side note: If you deploy this into a production environment, you should consider bundling these files. Downloading 4 files will impact your load time, so it's better to just bundle them together and send them over as a single file. While you're at it, you probably also want to minify it.

Upvotes: 1

Related Questions