SymfonyWorld Online 2021 Winter Edition December 9 – 10, 2021 100% Online 25 talks and 10 workshops

Moving <script> inside <head> and the "defer" Attribute

With the introduction of the Symfony UX Initiative a lot of cool things are happening in the Symfony world related to JavaScript. Stimulus already has great integration thanks to the Encore.enableStimulusBridge() feature and Turbo has huge potential to give an SPA-like experience with server-rendered HTML.

Related to this, I want to talk about a simple change that just happened to the symfony/twig-bundle recipe.

If you start a new project today, the location of the {% block javascripts %} in base.html.twig has moved from the bottom of the page up into <head>:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!-- templates/base.html.twig -->
<html>
<head>
{% block stylesheets %}{% endblock %}
+
+ {% block javascripts %}{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
- {% block javascripts %}{% endblock %}
</body>
</html>

Historically, this lived at the bottom of the page so that any <script> tags wouldn’t be executed until the page had already finished loading. This was for two reasons:

  1. When your browser sees a normal <script> tag, it waits (blocks the page) while that JavaScript is downloaded and executed.
  2. You often want the full HTML to already be available when your JavaScript executes.

So why did we move the javascripts block into <head>? Isn’t that worse? Actually, it’s better, as long as your script tags have the defer attribute.

<script src=”” defer>

When your browser sees a <script tag with a defer attribute, it treats it differently. First, it still starts downloading it immediately… but your browser does not wait for it to be downloaded before rendering the rest of the page: it is “non-blocking”. And second, after the JavaScript is downloaded, your browser waits until the page is fully-loaded before executing the JavaScript.

In other words: your browser starts downloading the file earlier (without blocking the page) but your code is still executed after the page is loaded: the same as having it at the bottom of the page.

So as long as you add the defer attribute, life is good! Well… except for “inline” JavaScript: it behaves differently.

The “Caveat”: Inline JavaScript Cannot be Deferred

When you use <script src="/app.js" defer>, that code will execute after the page finishes loading, just like if the <script> tag were at the bottom of the page. But inline JavaScript cannot be deferred.

Imagine you have an app.js file that creates a global variable:

1
2
3
4
5
// app.js
// set a global "App" variable
window.App = {
    // ...
}

And then you write some “inline” JavaScript in your template that uses it:

1
2
3
4
5
6
7
8
9
<html>
<head>
    <script src="/app.js" defer></script>
    <script defer>
        // try to use the App variable from app.js
        App.initializeSomething();
    </script>
</head>
<!-- ... -->

If you tried this, you’d get an error!

Uncaught ReferenceError: App is not defined

If you have multiple <script src="/..." defer> tags, they do render in order. The problem is that “inline” JavaScript cannot be deferred: it always executes immediately. This means that App.initializeSomething() is called before app.js.

If you have a lot of inline JavaScript like this, then you may not be able to use defer. No problem: keep your JavaScript at the bottom of the page without defer.

But the ideal solution is to move all of your inline JavaScript into external JavaScript files. This can sometimes be tricky if you want to pass a dynamic value into JavaScript. This can be fixed by setting a global variable and reading that in your external JavaScript:

1
2
3
4
5
6
7
8
9
<script src="/app.js" defer></script>

<script>
-     // JavaScript is "inline" so we can use Twig to pass a dynamic value
-     App.initializeSomething('{{ someDynamicValue }}');

+     // read this from app.js
+     window.SOME_DYNAMIC_VALUE = '{{ someDynamicValue }}'
</script>

In app.js, you can read window.SOME_DYNAMIC_VALUE. Another popular approach is to add data- attributes to an element and read them in JavaScript.

encore_entry_script_tags() and the “defer” Attribute

If you use Webpack Encore, then you probably don’t write your <script> tags by hand: you render them with the handy encore_entry_script_tags() Twig function. So, how can we add the defer attribute?

In WebpackEncoreBundle 1.9, you can specify - in webpack_encore.yaml - an array of attributes that you want to include on all script tags. To always add defer:

1
2
3
4
5
6
# config/packages/webpack_encore.yaml
webpack_encore:
    # ...

+   script_attributes:
+       defer: true

That’s it! No change needed to your templates. If you install WebpackEncoreBundle today, you’ll get this config automatically thanks its recipe.

Have any questions, let us know! We’ll soon cover all of this on SymfonyCasts.

Have fun!

Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

This change may break a lot of things. Please be careful how you deploy it to the wild.
Hey @Josef Kufner!

Yea, you're right: don't expect to make this change in your app and having everything work. You would have to check for inline JavaScript and (of course) QA things :).

For new projects (which is what the recipe change affects), you have a better opportunity to avoid inline JavaScript immediately and take advantage of the change :).

Cheers!
Thanks! A good stuff for next projects, and a good reason to forget what is the inline JS is))

Comments are closed.

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