0

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

4
Contributors
4
Replies
33
Views
4 Years
Discussion Span
Last Post by Violet_82
0

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.

0

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.

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.