Management command to compact javascript files

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import os
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('-m','--method', action='store', dest='method', 
            type='choice', choices=['jsmin', 'jspacker'],
            help='Packing or minimization method (jsmin/jspacker)'),
        make_option('-f','--file', action='append', dest='build_file', default=[],
            help='Build only this output file'),
    )
    help = "Builds minimized/compacted javascript files"
    
    def handle(self, *args, **options):
        from django.conf import settings
        
        try:
            method = getattr(settings, 'JSC_METHOD')
        except AttributeError:
            method = None
        method = options.get('method') or method or 'jsmin'
        build_files = options.get('build_file', [])
        try:
            path = getattr(settings, 'JSC_PATH')
        except AttributeError:
            raise CommandError("Missing JSC_PATH in settings")
        try:
            filesdef = getattr(settings, 'JSC_FILES')
        except AttributeError:
            raise CommandError("Missing JSC_FILES in settings")
        
        all_outfiles = [ outfilename for (outfilename, other) in filesdef ]
        for build_file in build_files:
            if not build_file in all_outfiles:
                raise CommandError("Output file %s not included in JSC_FILES settings" % build_file)
                
        #by default build all files
        if build_files == []:
             build_files = all_outfiles
        
        for outfilename, inputfilenames in filesdef:
            if outfilename in build_files:
                print "Building minimized %s" % outfilename
                build_minimized_file(path, outfilename, inputfilenames, method)

# Minimizes javascript using jsmin.py from http://javascript.crockford.com/jsmin.py.txt
# Packs using http://www.crowproductions.de/repos/main/public/packer/jspacker.py
def build_minimized_file(path, outfilename, inputfilenames, method):
    import jsmin
    import jspacker
    from StringIO import StringIO
    
    data = StringIO()
    for name in inputfilenames:
        try:
            f = file(os.path.join(path,name))
        except IOError:
            raise CommandError("Error reading %s" % os.path.join(path,name))
        data.write(f.read())
        data.write('\n')
    outfile = file(os.path.join(path,outfilename),'w')
    if method == 'jsmin':
        outfile.write(jsmin.jsmin(data.getvalue()))
    else:
        p = jspacker.JavaScriptPacker()
        outfile.write(p.pack(data.getvalue(), compaction=False, encoding=62, fastDecode=True))
    outfile.close()

More like this

  1. Publishing service endpoint uri to javascript by dberansky 3 years, 10 months ago
  2. Django view and url in one function by oduvan 4 years, 6 months ago
  3. Compact list_filter with counter by fab10m 3 years, 2 months ago
  4. Django Database Migration Management Script by paltman 5 years, 9 months ago
  5. Random code tag by aaloy 6 years, 9 months ago

Comments

Batiste (on April 18, 2008):

Packing javascript is not a good practice. The browser as to decompress it and that eat CPU. The time gained in download time is largely lost in decompressing the javascript. The worse part is that this decompression process as to be repeated on every single page so each page of your website is slower.

#

(Forgotten your password?)