@ecopages/scripts-injector

中文文档
0.1.5发布于 2026/03/05TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 4621

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.

原始使用文档
文档目录20 节
  1. Usage
  2. Web Component Examples
  3. Load on idle
  4. Load on interaction
  5. Load using injector map
  6. Global Injector Examples (No Web Component)
  7. 1) Define a global trigger map
  8. 2) Bind standard elements with data-eco-trigger
  9. 3) Initialize
  10. Props
  11. Latest Features
  12. Full Event Replay with Property Preservation
  13. Race Condition Prevention
  14. Load Reason Tracking
  15. Error Tracking
  16. Typical usage
  17. Alternative Usage: Multi-Trigger Configuration
  18. Supported Events
  19. Data Attributes
  20. Inspiration

Scripts Injector

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.

Usage

To use the Scripts Injector, you need to include it in your HTML:

<scripts-injector></scripts-injector>

Web Component Examples

Load on idle

<scripts-injector scripts="/analytics.js" on:idle>
    <div>Content</div>
</scripts-injector>

Load on interaction

<scripts-injector scripts="/heavy-chart.js" on:interaction="mouseenter,focusin">
    <button>Open chart</button>
</scripts-injector>

Load using injector map

<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>

Global Injector Examples (No Web Component)

1) Define a global trigger map

<script type="ecopages/global-injector-map">
{
    "analytics-trigger": {
        "on:idle": { "scripts": ["/_assets/tracker.js"] }
    },
    "card-trigger": {
        "on:interaction": {
            "value": "click",
            "scripts": ["/_assets/card-interactions.js"]
        }
    }
}
</script>

2) Bind standard elements with data-eco-trigger

<div data-eco-trigger="analytics-trigger"></div>
<button data-eco-trigger="card-trigger">Open Card</button>

3) Initialize

import { initGlobalInjector } from '@ecopages/scripts-injector/global';

const injector = initGlobalInjector();

// Call after SPA route changes / page swaps when new trigger-map tags or
// new [data-eco-trigger] elements are inserted by your framework.
injector.refresh();

// Call during app teardown if needed.
injector.cleanup();

initGlobalInjector() returns a handle with:

  • refresh() — re-parse all global maps and bind any unbound elements with data-eco-trigger
  • cleanup() — disconnect observers and disable further refresh work for that instance

Props

The ScriptInjectorProps type defines the properties that can be used to control the behavior of the scripts-injector custom element. Here are the available properties:

"on:idle": This optional boolean property determines whether the script should be loaded once the DOM is ready. For example, <scripts-injector on:idle></scripts-injector> will load the script as soon as the DOM is ready.

"on:interaction": This optional property allows you to specify a series of events that will trigger the loading of the script. It can be either "touchstart,click" or "mouseenter,focusin". For example, <scripts-injector on:interaction="mouseenter, focusin"></scripts-injector> will load the script when the user either mouses over the element or focuses on it.

"on:visible": This optional property can be either a string or a boolean. If it's a string, it should specify the root margin for an Intersection Observer that will load the script when the element comes into view. If it's a boolean and it's true, the script will be loaded when the element comes into view with a default root margin. For example, <scripts-injector on:visible="50px 1px"></scripts-injector> will load the script when the element comes into view, with a root margin of 50px 1px.

scripts: This property should be a comma-separated string of scripts to be loaded. For example, <scripts-injector scripts="script1.js,script2.js"></scripts-injector> will load script1.js and script2.js.

Latest Features

Full Event Replay with Property Preservation

For all interaction events, the Scripts Injector intercepts the initial event, prevents the default action, loads the required script, and then replays the event with all original properties preserved. This ensures that user actions are never lost, even if they happen before the script is fully loaded.

  • Click events: Use native .click() for best compatibility with links and forms
  • Mouse events: Preserve clientX, clientY, screenX, screenY, button, buttons, and modifier keys
  • Keyboard events: Preserve key, code, location, repeat, and modifier keys
  • Focus events: Preserve relatedTarget
  • Touch events: Preserve touches, targetTouches, changedTouches, and modifier keys

Race Condition Prevention

Multiple script injectors requesting the same script will coordinate to prevent duplicate loading. A static registry tracks scripts currently being loaded, ensuring only one network request is made even when multiple injectors trigger simultaneously.

Load Reason Tracking

After loading, the element receives a data-load-reason attribute indicating what triggered the load:

  • idle - Loaded via on:idle
  • visible - Loaded via on:visible
  • interaction:click, interaction:mouseenter, etc. - Loaded via the specific interaction event

Error Tracking

If any scripts fail to load, the element receives a data-error attribute containing the comma-separated list of failed script URLs. The DATA_LOADED event also includes a failedScripts array in its detail.

// Listen for load completion with error info
document.addEventListener('data-loaded', (event) => {
    const { loadedScripts, failedScripts } = event.detail;
    if (failedScripts.length > 0) {
        console.warn('Some scripts failed to load:', failedScripts);
    }
});

Typical usage

This passage provides a standard use case for the custom element. The script is designed to load when the user interacts with it, either through mouse entry or a focus event. If multiple script injectors are present with the same script, only the first one will execute the load. This is because once a script is loaded, all script injectors are notified and subsequently remove the script from their loading responsibilities.

<scripts-injector on:interaction="mouseenter,focusin" scripts={['path/to/my/element']}>
    <lit-counter class="lit-counter" count={8}></lit-counter>
</scripts-injector>

Alternative Usage: Multi-Trigger Configuration

To avoid deeply nested <scripts-injector> instances when different scripts inside a single component require different triggers, you can use the JSON map configuration approach. This allows you to flatten the DOM structure and configure multiple triggers simultaneously on a single injector element:

<scripts-injector>
    <script type="ecopages/injector-map">
        {
            "on:idle": { "scripts": ["/_assets/tracker.js"] },
            "on:interaction": {
                "value": "click",
                "scripts": ["/_assets/heavy-ui.js"]
            }
        }
    </script>
    <!-- Component Content -->
    <div class="my-component">...</div>
</scripts-injector>

Supported Events

The on:interaction prop supports a wide range of DOM events, as defined in InteractionEvent.

  • Mouse: click, dblclick, mousedown, mouseup, mouseenter, mouseleave, mousemove, mouseover, mouseout
  • Touch: touchstart, touchend, touchmove, touchcancel
  • Focus: focus, blur, focusin, focusout
  • Keyboard: keydown, keypress, keyup
  • Form: input, change, submit
  • UI: scroll, resize

Data Attributes

After script loading completes, the following attributes are set on the element:

AttributeDescription
data-loadedPresent when all scripts have been loaded (or attempted)
data-load-reasonThe trigger that caused scripts to load (idle, visible, interaction:<event>)
data-errorComma-separated list of script URLs that failed to load (only if errors occurred)

Inspiration

This is undeniably heavily influenced by 11ty/is-land, Astro island and the "component island" concept, originally introduced by Etsy's frontend architect, Katie Sylor-Miller.

版本与发布记录

@ecopages/scripts-injector 共发布 6 个版本,首次发布于 2024/06/02;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.5latest2026/03/058 个月前
0.1.42026/03/038 个月前
0.1.32026/02/029 个月前
0.1.22025/12/2010 个月前
0.1.12024/06/022 年前
0.1.02024/06/022 年前

关于 @ecopages/scripts-injector 的常见问题

@ecopages/scripts-injector 是什么?

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.

如何安装 @ecopages/scripts-injector?

在项目目录运行 npm install @ecopages/scripts-injector,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typescript(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ecopages/scripts-injector 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ecopages/scripts-injector 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ecopages/scripts-injector 可以商用吗?

@ecopages/scripts-injector 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@ecopages/scripts-injector 的下载量有多少?

根据 npm 官方下载统计,@ecopages/scripts-injector 在 2026/10/13 – 2026/11/11 这 30 天内被下载 4,621 次,日均约 154 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ecopages/scripts-injector 还在维护吗?

最新版本 0.1.5 发布于 2026/03/05(8 个月前);至今共发布 6 个版本,其中过去 12 个月发布了 4 个;首次发布于 2024/06/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。