Login

Management command to compact javascript files

Author:
pedrolima
Posted:
January 23, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Uses jsmin or jspacker to compact javascript files (usage example in this blog post)

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.

#

Please login first before commenting.