In my website, www.trailbehind.com, we have a set of javascript files that belong on all pages. And then some pages include additional libraries.
For the JS files that all pages uses (there are a couple dozen files), we concatenate them and minify them on build.
There is a flag in our settings file that says whether to use the concatenated javascript or the separate files on build. This is critical so that you can debug the javascript on dev, but use the small, single-file javascript on production.
Here is our python code to combine and minify:
import os
import thetrailbehind.lib.jsmin as jsmin
JS_FILES = [ 'lib/json2.js',
'lib/markermanager.js',
'lib/labeledmarker.js',
'lib/rsh/rsh.js',
'lib/showdown.js',
'lib/yui.js',
'lib/dragzoom.js',
'gen/attribute_data.js',
'gen/national-parks.js',
'Widgets/CommentsWidget.js',
'Widgets/Search.js',
'Widgets/MenuWidget.js',
'Widgets/PhotoWidget.js',
'Widgets/ReportList.js',
'Widgets/help.js',
'attributes.js',
'rsh.js',
'map.js',
'mapcontrols.js',
'markers.js',
'amazon.js',
'plan_trip.js',
'init.js',]
def concat(files, base_path, all_file, all_file_min):
if os.path.exists(base_path + all_file):
lasttime = os.path.getmtime(base_path + all_file)
else:
lasttime = 0
out_of_date = False
for file in files:
if os.path.getmtime(base_path + file) > lasttime:
out_of_date = True
break
if out_of_date:
outfile = open(base_path + all_file, 'w')
for file in files:
outfile.write(open(base_path + file).read())
outfile.write("\n")
outfile.close()
alljs = open(base_path + all_file)
allminjs = open(base_path + all_file_min, "w+")
jsmin.JavascriptMinify().minify(alljs, allminjs)
alljs.close()
allminjs.close()
def main():
concat(JS_FILES, '/home/wibge/thetrailbehind/media/javascript/', 'gen/all.js', 'gen/all.min.js')
if __name__ == "__main__":
main()
And here is the Django/HTML template where we switch:
{% if use_all_js %}
script type=text/javascript src=/site_media/javascript/gen/all.min.js>
{% else %}
script type="text/javascript" src="/site_media/javascript/rsh.js">
script type="text/javascript" src="/site_media/javascript/amazon.js">
script type="text/javascript" src="/site_media/javascript/map.js">
A BUNCH OF SEPARATE INCLUDES...etc
{% endif %}