tags:

views:

152

answers:

3

I want to concatenate javascript files together and serve them as one from my site - so thats my code and jquery plugins or other 3rd party scripts. (I'm using google CDN for hosting of jQuery).

I was wondering i this is always guaranteed to be a safe thing to do. I'm not an expert in Javascript as far as things like namespacing goes and I was just a little worried that it might be possible to have something - like a namespace construct that could cause a conflict. I'm fine in assuming that the javascript is all well formed from each source.

As far as I know a <script> tag essentially just sticks the JS in place as if it was in the file, but I wondered if theres any boundary cases where this isn't true.

I'm aware that concatenation of files is something that is common and used by javascript frameworks such as Yahoo's YUI - but obviously they have full control of their files.

A: 

As long as you concatenate them in the correct order you should be safe. The correct order is the same order as you load them in today.

krosenvold
so there is no such thing as anything being 'file scoped' in javascript?
Simon_Weaver
@Simon that's correct
Greg
@simon: the host object is shared on a window/frame level - files are irrelevant in this regard...
Christoph
+1  A: 

I'd have to agree with krosenvold no reason why it shouldn't work that I can think off. Just make sure you watch your global variables and function names, they could cause problems if you get the scripts from multiple non-collaborating sources.

Shraptnel
ya! javascript is scary. i'm sure this is a much more like source of a clash. its not like i'm not going to stop testing. i just wanted to make sure that there were no subtleties of concatenating dynamically .js files server side - especially since i presented my concatenating code for others to use
Simon_Weaver
+2  A: 

You may run into syntax errors around semi-colons.

file A:

var foo = 3 // END OF FILE

file B:

var bar = 4 // BEGINNING OF FILE

file A+B:

var foo = 3var bar = 4

Easily solved by just jamming a semi-colon between each file you are concatenating.

Crescent Fresh
cunning :) nice observation. thanks
Simon_Weaver