Question

I admit, I don't know too much about javascript, mostly I just "steal and modify" from Javascript.com and Dynamic Drive.
I've run across a few scripts that call two .js files

<script type="text/javascript" src="lib/prototype.js">  
</script>
<script type="text/javascript" src="src/aptabs.js">  
</script>  

and was wondering why, can I safely merge them both with my external javascript or is there a sort of incompatibility that prevents all the code from sharing the same file?

Was it helpful?

Solution

It's actually better performance wise to have them both in the same file- Depending on how your site is architected. The principle is to reduce the number of http requests, as each one carries some overhead.

That said, that's something best left to the very end of production. During development it's easier to have everything seperate. If you're going to join them, it's best to have an automated build script to do the operations.

OTHER TIPS

It's often good to separate code with different concerns. Those two files might come from different places. Say prototype is upgraded and you want the new goodness. Then you can just replace the prototype.js file on your server rather than editing your huge file and do the surgery on it.

EDIT: It's also "nicer" for the browser to be able to cache the files individually. If your question comes from a concern of duplicating that block of code in several html files I suggest you make one snippet of it from the server side and include it your html files through whatever means you have at hand/feel comfy with.

I'm pretty sure the javascript has no idea which file it has loaded from, so there shouldn't be a problem merging it, however...

Personally, I'd keep them separate. It will make it simpler to co-ordinate versioning etc. For most repeat visits, the script will be cached by the browser anyway, so 2 vs 1 isn't really a huge issue. But when you do upgrade one (or the other), the client only needs to download half as much. But again, since it is generally cached it isn't a biggie!

So for simplicity - keep the scripts in their original forms. Given your opening comment "I don't know too much about javascript", this is by far the best approach; I don't mean that disparagingly - simply that if something goes wrong, you don't want to have to find if you broke it, or it was broke already.

Edit: it also makes it easy to re-order, for example if you are using two scripts that use the same terminology like $ in jQuery, which also supports a mode with the explicit naming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top