From bb34081599b0a7328e2c1fa0ba9463e5d5f603c6 Mon Sep 17 00:00:00 2001 From: Chris Hill-Scott Date: Thu, 3 Dec 2020 10:52:25 +0000 Subject: [PATCH] Tell browser to connect to asset domain earlier When a browser loads a Notify page it does the following: - DNS and TLS handshake for notifications.service.gov.uk - download some HTML - sees that the HTML needs to load some CSS - DNS and TLS handshake for static.notifications.service.gov.uk - downloads the CSS We can speed things up a bit in modern browsers by parallelizing this process a bit. Modern browsers support some HTTP headers[1] that allow them to connect to other origins sooner. After this change the steps are: - DNS and TLS handshake for notifications.service.gov.uk - receive response headers and simultaneously: - download some HTML - DNS and TLS handshake for static.notifications.service.gov.uk - sees that the HTML needs to load some CSS - downloads the CSS 1. https://developer.mozilla.org/en-US/docs/Web/Performance/dns-prefetch --- app/__init__.py | 5 +++++ tests/app/main/views/test_headers.py | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 561b322f8..4c7b35cf9 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -630,6 +630,11 @@ def useful_headers_after_request(response): logo_domain=get_logo_cdn_domain(), ) )) + response.headers.add('Link', ( + '<{asset_url}>; rel=dns-prefetch, <{asset_url}>; rel=preconnect'.format( + asset_url=f'https://{current_app.config["ASSET_DOMAIN"]}' + ) + )) if 'Cache-Control' in response.headers: del response.headers['Cache-Control'] response.headers.add( diff --git a/tests/app/main/views/test_headers.py b/tests/app/main/views/test_headers.py index 003a208c1..9bbba9f17 100644 --- a/tests/app/main/views/test_headers.py +++ b/tests/app/main/views/test_headers.py @@ -24,6 +24,10 @@ def test_owasp_useful_headers_set( " *.notifications.service.gov.uk static-logos.test.com data:;" "frame-src 'self' www.youtube-nocookie.com;" ) + assert response.headers['Link'] == ( + '; rel=dns-prefetch, ' + '; rel=preconnect' + ) def test_headers_non_ascii_characters_are_replaced(