Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Introduce a mechanism to register and enqueue scripts #43023

@jonkoops

Description

@jonkoops

One of the main issues we have with scripts in various templates, is that they are directly placed inside the template as a <script> tag. This makes it difficult to:

  • Ensure a script is only loaded once, as it might be included from multiple templates.
  • Ensure a script is loaded only when needed (e.g. a script might be included on every page, only to be used on a sub-set of templates).
  • Add security critical attributes to the <script> tag, such as integrity, or handle Content Security Policy in a uniform manner.
  • Identifying scripts that provide module imports, and placing them in the import map.
  • Preloading scripts that will be requested later on as a dependency (e.g. rel="modulepreload").

We therefore need to introduce a mechanism to register scripts, and enqueue them when they are needed, and in the right place. There has been some previous discussion on this subject under #22042 (comment), and I would like to work towards an API proposal we can settle on.

One popular open-source project that offers a similar functionality is WordPress, it has an API to something similar to what I would be interested in implementing here:

We can use this API as a reference to get some ideas, but we should take the opportunity to follow some best practices in regard to where scripts are loaded, and what their default attributes should be (e.g. type="module").

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions