Assets

Lazy Assets

Lazy assets load only when matching markup exists on the page.

Load JavaScript When Needed#

Put browser libraries in their own files when they only serve one kind of markup. Then mark the asset with data-load-when.

phpresources/views/layouts/default.php
<head>  <link rel="stylesheet" href="main.css">  <script    type="module"    src="highlight.js"    data-load-when="pre code"  ></script></head>

TemplateX keeps highlight.js out of the first page load. If the page contains pre code, the browser imports the built Vite file. If it does not, no highlight JavaScript is requested.

Load CSS When Needed#

The same attribute works on local stylesheets:

phpresources/views/layouts/default.php
<link rel="stylesheet" href="carousel.css" data-load-when=".carousel">

Use this for optional features such as syntax highlighting, sliders, maps, or other libraries that only make sense when matching markup is present.

Keep global CSS in main.css, and keep global JavaScript in main.js.

Lazy Entries#

Lazy assets are separate Vite entries.

CSS imported by a lazy JavaScript file is split with that feature instead of being forced into the main stylesheet.