Saturday, October 12, 2013

How to Automate JavaScript Minification on App Engine (Python)


You can automate the process pretty efficiently by loading the content of your script into a string, processing it with jsmin and finally save and serve the result.
you can grab jsmin.py here.
lets say I have this function that reads the JS from the filesystem (uncompressed, debug version) and returns it's string content in the logger.py module:
class ScriptManager():
    def get_javascript(self):
        path_to_js = os.path.join(os.path.dirname(__file__), 'js/script.js')
        return file(path_to_js,'rb').read()
process it over with jsmin. make sure to use proper caching headers. take this jsrendered sample module as an examp
js_compressed =
jsmin.jsmin(scripts.logger.ScriptManager().get_javascript())

JS_CACHE_FOR_DAYS = 30

class scriptjs(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/javascript'
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(JS_CACHE_FOR_DAYS)
        expires_str = expires_date.strftime('%d %b %Y %H:%M:%S GMT')
        self.response.headers.add_header('Expires', expires_str)
        self.response.headers['Cache-Control'] = 'public'
        self.response.cache_control.no_cache = None
        self.response.out.write(js_compressed)
now return that from a dynamic contnet handler in your main.py:
 app = webapp2.WSGIApplication([
     ('/scripts/script.js', jsrender.scriptjs),...

No comments:

Post a Comment