Global Script Injector
While the <scripts-injector> custom element provides a powerful declarative approach to lazy-loading scripts by encapsulating logic within a Web Component, there are scenarios where a non-web-component solution is preferable to maintain a cleaner DOM structure or to aggregate script loading rules globally.
To accommodate these use cases, we provide the Global Script Injector.
What is it?
The Global Script Injector utilizes a centralized JSON configuration (<script type="ecopages/global-injector-map">) and plain HTML data-eco-trigger attributes. It leverages the exact same robust interaction-tracking and intersection-observer logic as the <scripts-injector>, but completely decoupled from custom elements.
Configuration
Define a single global JSON map that associates arbitrary "trigger IDs" with their respective loading conditions (on:idle, on:interaction, on:visible) and target scripts:
<script type="ecopages/global-injector-map">
{
"analytics-trigger": {
"on:idle": {
"scripts": ["/_assets/tracker.js"]
}
},
"complex-ui-loader": {
"on:interaction": {
"value": "mouseenter,focusin",
"scripts": ["/_assets/heavy-ui.js"]
},
"on:visible": {
"value": "200px",
"scripts": ["/_assets/lazy-image.js"]
}
}
}
</script>HTML Attributes
Any standard HTML element can opt into these triggers by referencing the keys from the global map using a data-eco-trigger attribute. This keeps your component structure pristine without deeply nesting wrapper elements.
<!-- Loads analytics.js on idle as defined in the global map -->
<div class="page-wrapper" data-eco-trigger="analytics-trigger">...</div>
<!-- Loads heavy-ui.js on hover and lazy-image.js when visible -->
<button data-eco-trigger="complex-ui-loader">Load Complex UI</button>Initialization
Unlike the Web Component which autoregisters, the Global Injector must be explicitly initialized. Provide this in your main entrypoint or layout component:
import { initGlobalInjector } from '@ecopages/scripts-injector/global';
const injector = initGlobalInjector();
// Example: wire into your framework/router lifecycle
router.onAfterNavigate(() => {
injector.refresh();
});
app.onDispose(() => {
injector.cleanup();
});Behind the scenes, initGlobalInjector will:
- Parse your
<script type="ecopages/global-injector-map">blocks. - Query the DOM for any
[data-eco-trigger]elements. - Observe the DOM for any newly added elements via a
MutationObserver. - Return a handle with
refresh()andcleanup()so your framework controls lifecycle integration. - Bind
on:idle,IntersectionObserver(on:visible), and DOM event listeners (on:interaction), with the same loading and replay rules as the Web Component.
Interaction Replay
An on:interaction listener runs in the capture phase on the trigger element:
- Scripts not loaded yet: the event is stopped and its default action prevented, the rule's scripts are loaded, and the event is replayed on the element the user actually targeted (
composedPath()[0], so this works inside shadow DOM). Aclickis replayed with.click(), so links and form submission still work. Any other event, includingkeydownandkeyup, is replayed as a clone with its original properties. The trigger element itself can be the target. - Scripts still loading (started by another element): the event is held until the load finishes, then replayed.
- Scripts already loaded, for example by another element with the same trigger id: the event passes through untouched, so the first Enter or click on a second instance works.
The listeners are removed after the first load, so later events are never intercepted.
Data Attributes
| Attribute | Description |
|---|---|
data-eco-bound | Present once the element's listeners and observers are in place |
data-eco-bound-trigger | The trigger id the element is bound to; when data-eco-trigger changes, the element is rebound |
data-loaded-scripts | Comma-separated list of script URLs loaded for this element |
data-loaded | Present when every script referenced by the element's trigger has loaded (or failed) |
data-load-reason | What triggered the last load (idle, visible, interaction:<event>) |
data-error | Comma-separated list of script URLs that failed to load (only if errors occurred) |
Compatibility & Deduplication
The Global Injector and <scripts-injector> can be used side by side. They share their script loader and coordinate through the <script> tags themselves, so a script requested by both is fetched once, and a script that is still loading is waited on rather than treated as loaded.
Trusted Types
Script URLs are assigned as plain strings. Pages that enforce require-trusted-types-for 'script' need a default policy; see Trusted Types in the main docs.