New in Symfony 3.3: Asset preloading with HTTP/2 Push

Contributed by
Kévin Dunglas
in #21478.

One of the most relevant new features proposed by HTTP/2 to improve the loading of web pages is called Server Push. HTTP/2 Push allows a web server to send resources to a web browser before the browser gets to request them.

In Symfony 3.3 we added HTTP/2 Push support for web assets (CSS, JS, images) to allow preloading them as explained in the Preload W3C Working Draft. In practice, and following the traditional Symfony philosophy of using composition, the new feature is enabled by wrapping your assets with the new preload() function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<head>
    {# by default, assets are pushed #}
    <link href="{{ preload(asset('/css/app.css')) }}">
    {# ... but you can disable pushing... #}
    <link href="{{ preload(asset('/css/app.css'), { nopush: true }) }}">
    {# ... and you can also explicit the asset type #}
    <link href="{{ preload(asset('/css/app.css'), { as: 'style' }) }}">
    ...
</head>
<body>
    ...
    <script src="{{ preload(asset('/js/app.js')) }}"></script>
</body>

Behind the scenes, the preload() function adds a Link HTTP header that is processed by intermediate proxies compatible with HTTP/2:

1
2
3
4
HTTP/1.1 200 OK
Content-Type: text/html
...
Link: </css/app.css>; rel=preload,</cjs/app.js>; rel=preload

An added bonus of using this technique is that all those assets are downloaded using just one connection, improving the page speed dramatically.

Comments

Nice, thanks @kėvin.
Please note that you should always include the `as` attribute when applicable (https://fetch.spec.whatwg.org/#concept-request-destination).

Also, CloudFlare has built-in support for this feature, it means that if you use CloudFlare (even the free plan) in front of your Symfony application, you'll get HTTP/2 push automatically.
Awesome !
Thanks @Kavier
Awesome!
Are there already best practises on when to (and when not to) server-push assets?
Wow! Awesome!
@Alexander, always push assets required to render initially the full page (main JS, CSS and images files).
Hi, thanks for that feature!
According to the Twig Asset extension the syntax needs to be
instead of

and an optional third (boolean) parameter for the push thingy.
Muy buena opción, gracias por ese feature. Todo para mejorar el rendimiento siempre es bueno, y en este caso disminuir las conexiones es muy importante.
@Kévin, If I did this, I would preemtively push files to the browser that probably have already been cached by the browser. I'm not convinced that it is that easy to decide. That's why I'm asking.
Awesome!
Will this be made compatible with Assetic also?

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.