Sean Thoman
Sean Thoman

Reputation: 7499

Organizing library dependencies in JavaScript best practice

What are peoples thoughts on the best way to organize dependencies in javascript? I know the basics but have some more specific questions. From reading Douglas Crockford and other posts around here, I know to put script tags as late in the body as possible,use minifying, combining all the client-side code into one .js file where applicable, etc.

What is the best way to use libraries though? Say for instance you do the following:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="somelib.min.js"></script>
<script type="text/javascript" src="myappcode.min.js"></script>

Could this be considered too many script tags? Say that myappcode.min.js is dependent on but also modifies certain parts of somelib.min.js -- should you just combine those into one file?

Also is it possible or even a good idea to reference one .js file such as a library inside another .js file, as opposed to just putting one script tag before another in order to reference it in the latter? Coming from a C# background I know that JavaScript is parsed sequentially as opposed to starting in a main() method and proceeding -- so I am guessing the script approach is pretty standard, but wanted to make sure.

Upvotes: 1

Views: 284

Answers (2)

JesseBuesking
JesseBuesking

Reputation: 6596

It depends on the person looking at it. I don't think 3 script tags is bad, although it's known that reducing the number of HTTP requests improves a websites loading speed (as it decreases the overhead of each individual request).

I would not merge files just for the sake of merging them in my development project. When uploading to a production server however, I'd merge the files together to reduce the number of script tags necessary as you shouldn't care about readablity/etc in a production environment.

Upvotes: 1

Trott
Trott

Reputation: 70183

You can merge those JavaScript tags into a single tag while still being able to keep all the JS library files separate if you write a JavaScript handler. Check the code for the JS handler in the UC Mobile Web Framework for an example of how you might do this.

Upvotes: 1

Related Questions