Middleware to move tags <script> to the bottom

 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
import re


FIND_SCRIPT_TAGS = re.compile(r'(<script .*?>.*?</script>)', re.DOTALL)

class ScriptsAtBottomMiddleware(object):
    """Finds all tags <script> at the HTML response and move to the end of the document,
    before tag </html>.
    
    This makes the page load faster, because <script> blocks parallel loading.
    
    Read more about this at:
        - http://developer.yahoo.com/performance/rules.html#js_bottom
        - http://code.google.com/intl/pt-BR/speed/page-speed/docs/rtt.html#PutStylesBeforeScripts
    """

    def process_response(self, request, response):
        if response['content-type'][:9] == 'text/html':
            # Find scripts tags with src
            f = FIND_SCRIPT_TAGS.findall(response.content)
            
            # Remove the tags found
            for tag in f: response.content = response.content.replace(tag, '')
            
            # Insert the tags found at the bottom
            pos = response.content.find('</html>')
            response.content = response.content[:pos] + '\n'.join(f) + '\n' + response.content[pos:]

        return response

More like this

  1. head inclusion middleware by bowdengm 2 years, 11 months ago
  2. Django template object jsonify by nmk 3 years, 1 month ago
  3. YUI Loader as Django middleware by akaihola 3 years, 9 months ago
  4. A dict template tag by Batiste 3 years, 9 months ago
  5. AddThis Social Networking TemplateTag by yeago 3 years, 1 month ago

Comments

springlo (on November 4, 2010):

我要拜你为师。

#

(Forgotten your password?)