Decision Load JavaScript libraries conditionally

accepted

Loading all JavaScript globally increases initial page weight and slows down pages that don't need it.

Decision

Attach JavaScript libraries at the entity or component level using Drupal's libraries API so they only load when the content that needs them is present on the page.

For example, a video paragraph template should declare the Vimeo API as its own library dependency rather than loading it site-wide.

SDC components already handle this for co-located CSS and JS, which are auto-discovered and loaded only when the component renders.

Exceptions

Libraries required on every page (analytics, error tracking, global navigation) should remain in the theme or module global library. When in doubt, measure: if a library is used on more than 80% of pages, global loading may be simpler without meaningful performance cost.

Consequences

  • Initial page load is lighter — JavaScript only loads when needed
  • Entity and paragraph templates become responsible for declaring their own library dependencies
  • Developers must verify that conditionally loaded libraries are attached in all relevant templates

Additional Resources