Login

Middleware to move tags <script> to the bottom

Author:
marinho
Posted:
July 9, 2010
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

This middleware makes the page load faster because it moves all tags <script> to the end of document.

When a tag <script> loads, it blocks parallel loading, so, the best practice is load them after load CSS and images.

To use it, just put in a file and add to your setting MIDDLEWARE_CLASSES.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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, 6 months ago

Comments

springlo (on November 4, 2010):

我要拜你为师。

#

pkoch (on March 13, 2012):

Careful! You're making various copies of the response's content string! I think you might be trading server performance for client performance.

Wouldn't it be simples/more efficient to have a delayed script tag?

#

Please login first before commenting.