Moving

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:

When your browser sees a normal <script> tag, it waits (blocks the page) while that JavaScript is downloaded and executed. 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 your 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!

                Sponsor the Symfony project.

http://feedproxy.google.com/~r/symfony/blog/~3/TKCr0S6v7Mk/moving-script-inside-head-and-the-defer-attribute

Établi 5y | 19 janv. 2021, 14:20:26


Connectez-vous pour ajouter un commentaire

Autres messages de ce groupe

A Week of Symfony #972 (August 11–17, 2025)

This week, development activity mostly focused on dealing with the deprecation of sleep/wakeup methods in PHP 8.5 and their replacement by serialize/unserialize methods. In addition, we published more

17 août 2025, 08:30:06 | Symfony
Let’s build the Symfony AI ecosystem together

It’s been only in July that we published symfony/ai and kicked off our AI initiative, but the repository has been busy since day one. Over 500 stars, more than 200 pull requests & issues, trending

16 août 2025, 09:30:03 | Symfony
SymfonyCon Amsterdam 2025:   Unconference Track at SymfonyCon Amsterdam 2025

🎤 Take the stage at SymfonyCon Amsterdam 2025, on your own terms!

The Unconference track is back and more dynamic than ever!

This unique, participant-driven format invites attendees to shape

12 août 2025, 12:40:20 | Symfony
A Week of Symfony #971 (August 4–10, 2025)

This week, Symfony completed the migration to PHPUnit 12 in the 7.4 branch, which required many changes during the past weeks, such as replacing annotations with attributes. In addition, we updated th

10 août 2025, 09:40:09 | Symfony
SymfonyCon Amsterdam 2025:  Join the Symfony Hackathon:  Collaborate, Contribute, Create

🧑‍💻HACKDAY IS COMING!

Get ready to code, collaborate, and contribute, Symfony Hackday is back!

Join us in Amsterdam on Saturday, November 29th, for a hands-on hackathon designed to bring the

6 août 2025, 10:40:04 | Symfony
A Week of Symfony #970 (July 28 – August 3, 2025)

This week, Symfony released the maintenance versions 6.4.24, 7.2.9, and 7.3.2. Meanwhile, we began deprecating the XML configuration format in some components, enhanced the YAML configuration format t

3 août 2025, 08:30:03 | Symfony
Symfony 6.4.24 released

Symfony 6.4.24 has just been released. Read the Symfony upgrade guide to learn more about upgrading Symfony and use the SymfonyInsight upgrade reports to detect the code you will need to change in you

31 juil. 2025, 13:10:32 | Symfony