Skip to content

Instantly share code, notes, and snippets.

@nitriques
Last active October 30, 2016 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitriques/1af283797bba38c4b01bdd1371cb0928 to your computer and use it in GitHub Desktop.
Save nitriques/1af283797bba38c4b01bdd1371cb0928 to your computer and use it in GitHub Desktop.
How to properly concat js files

That tweet created some responses and since 140 chars is not enough to explain how to do it, I decided to posted here.

First and formost, if not properly done, blindly concatenating javascript files can cause problems and will prevent the rest of your code to execute. This is by design: the js code must halt when it encounters and exception. But there are places (read API) where this rule is encapsulated, meaning that the error will halt only the current stack of execution.

That's the main thing: do not call you code, ever, to run in the first stack execution.

Create simple "module", scoped into an IIFE, which ends with a semi-colon (always)

(function (libX) {
   // my code
})(window.libX);

And never actually call any other function that a main central point which uses events. If I where to use jQuery, I would used the DOMReady event

(function ($) {
   var init = function () {
    // do things
   };
   $(init);
})(window.jQuery);

Concatenating multiple files like this will never fail.

And finally, yes it all comes down to those nasty syntax errors. Is usign a linter (not a transpiler) really that an overhead ? How I mean, did the programmer tested it ? :P

I've been doing this since 2009 and never had a problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment