The Scripts Injector is a custom element designed to dynamically load scripts into your web page. It provides a way to load scripts based on certain conditions and events, significantly improving page load performance by deferring non-critical resources.
To use the Scripts Injector, include the custom element in your project:
<scripts-injector></scripts-injector>npm install @ecopages/scripts-injectorLoad non-critical scripts (e.g., analytics) when the browser is idle.
<scripts-injector scripts="analytics.js" on:idle>
<!-- Content -->
</scripts-injector>Load heavy interactive scripts only when the user interacts (e.g., click, hover).
<scripts-injector scripts="heavy-chart.js" on:interaction="mouseenter,focusin">
<button>Show Chart</button>
</scripts-injector>Load scripts when an element enters the viewport.
<scripts-injector scripts="lazy-image.js" on:visible="50px">
<img src="..." />
</scripts-injector>To prevent deeply nested injectors when combining multiple triggers, you can provide an internal <script> tag mapping.
<scripts-injector>
<script type="ecopages/injector-map">
{
"on:idle": { "scripts": ["/_assets/tracker.js"] },
"on:interaction": {
"value": "click",
"scripts": ["/_assets/heavy-ui.js"]
}
}
</script>
<div class="my-component">...</div>
</scripts-injector>Use a global JSON map plus data-eco-trigger attributes when you want lazy loading without wrapping markup in a custom element.
<script type="ecopages/global-injector-map">
{
"analytics-trigger": {
"on:idle": {
"scripts": ["/_assets/tracker.js"]
}
},
"hero-trigger": {
"on:interaction": {
"value": "mouseenter,focusin",
"scripts": ["/_assets/hero-effects.js"]
},
"on:visible": {
"value": "100px",
"scripts": ["/_assets/hero-visual.js"]
}
}
}
</script><div data-eco-trigger="analytics-trigger"></div>
<section data-eco-trigger="hero-trigger">
<h2>Interactive Hero</h2>
</section>import { initGlobalInjector } from '@ecopages/scripts-injector/global';
initGlobalInjector();For detailed documentation, visit the Web Component docs and Global Injector docs, or run the demo app.