I've been doing a small web application, adding behaviors and appending DOM objects in Javascript using jQuery. The problem is that the code is starting to grow really fast and I don't know where to store it (either in the same page it's being used, or in a big js file). At this point, I have:
Now, you may be killing me with your eyes, and I know. This is definitely not a good (or at least not consistent) way to store Javascript. So, my question is:
Is there a best way to organize Javascript code?
I suppose that at least I should follow a rule, though the problem is that I'm not sure if it's best to have a js file for all the "global data and methods" and then store the other ones in smallers js files or , or simply give up and go for a tea.
What do you guys think? Thanks in advance!
PS: Obviously code reutilization is a good point. However, the scripts I will be reusing the most are saved in the first js file (the one with global stuff).
I usually store global scripts in a single common file, and each page has its separate script file.
You can store page specific script files along with the page (in the same folder) or replicate the directory structure of the site inside a common "scripts" folder (useful if you have many many script files), both ways I have the script files named as their page counterpart, to make mappings easy.
Also, you can use namespaces to further organize your code.
There's no hard and fast answer to this one, but one thing to bear in mind is that if you put as much javascript as possible in external files, it can be cached which will make subsequent visits to the page faster.
The rules I tend to follow are:
</body>
tag. This is because when the browser encounters a <script>
tag it will stop rendering the page and evaluate the script before continuing. This can make the page feel slower to the user (though there's no actual difference in load time, perception matters!) EDIT: If you are including a lot of javascript files in a page then it is worth looking into consolodating them into a single file. This is because every <script src="...">
tag in a page will trigger a HTTP request, and the specs say that there can only ever be two requests open per domain at any one time. Putting them all in a single file will also increase the benefit you will get from using a JS compressor such as closure or YUI, and the benefits from using mod_gzip
yslow is a good tool for determining optimizations to speed up page loading, it has plenty of advice to offer regarding javascript file optimizations. .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With