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.

Community
  • 1
  • 1
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689

3 Answers3

3

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
  • 115,249
  • 25
  • 154
  • 140
1

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.

fauxCoder
  • 364
  • 5
  • 15
  • 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 Jan 28 '09 at 12:41
0

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
  • 75,535
  • 32
  • 152
  • 208