Hi all, I was wondering if anybody can enlighten me on when it is best to separate javascript code in different script. Let me give you a practical example.
I have a script that I would like to run everytime the page is resized, so I am thinking to use the onresize event. But I also have some code that I will need to run when the DOM is ready, so I will wrap it inside a $(document).ready(function(){...});
I believe the script that is run onresize doesn't need to be inside a document ready, so is it worth splitting the 2 scripts into 2 separate files?
From here, in general, is it fair to say that the portion of a script that doesn't need to be inside a document ready should be in its own file and the same for the portion that needs to be inside a document ready (even if the one script could potentially call a function in the other file)?
thanks

Recommended Answers

All 4 Replies

Not sure about best practice, but I put them together so the browser only needs to load a single file.

I do not know if there is a hard and fast rule about when to break JavaScript code blocks into separate files.

If you are doing this work for an employer, they may have policies regarding when and how to break code up into individual files.

Myself, I often break code up by common sub-routines. For example, I have separate files for routines that (i) input data for a square matrix, (ii) output a square matrix, (iii) input a vector, (iv) output a vector, etc. That way, when I write a new page that may need these tasks done, I don't have to include the whole routine in each new program. I just reference the external .js file. Makes the file size of each page smaller, and saves space on the server.

Plus, using external files make re-loading the pages faster. The .js files are kept in the browser cache and don't have to be re-loaded each time.

It depends. It's a good practice to consolidate your scripts if possible. Saves on downloading time. However, you also wouldn't want one big fat file to download if the current page only uses 10% of the code in the external file.

In my case I do a lot of internal web apps so I do like to separate the files for organizational purposes since bandwidth on the LAN is not a factor. For Internet web, I do try to consolidate and minify where it makes sense.

ok thanks guys, so I seem to understand that it needs to be looked at on a case by case, thanks for your inputs
cheers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.