You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Livewire组件加载时加载JS文件?使用@push仍未生效

在Livewire组件加载时正确加载JS文件的方法

先排查基础问题:主模板是否配置了@stack('scripts')

你用@push('scripts')的前提是,主布局模板(比如layouts/app.blade.php)里必须存在对应的@stack('scripts')标记,且要放在</body>标签之前的位置,否则组件推送的脚本没有挂载目标。

主模板示例代码:

<!-- 页面其他内容 -->

@stack('scripts')
</body>
</html>

针对Livewire动态加载场景的解决方案

如果组件是延迟加载、或通过wire:load等方式动态渲染的,单纯的@push可能无法触发脚本加载,可通过以下两种方式处理:

方式一:用wire:init触发脚本加载

在组件blade文件中,通过wire:init调用自定义函数动态创建脚本标签:

<div wire:init="loadBootstrapJS">
    <!-- 组件内容 -->
</div>

@push('scripts')
<script>
function loadBootstrapJS() {
    // 检查脚本是否已加载,避免重复引入
    const existingScript = document.querySelector('script[src="{{ url('/assets/js/bootstrap.bundle.min.js') }}"]');
    if (!existingScript) {
        const script = document.createElement('script');
        script.src = "{{ url('/assets/js/bootstrap.bundle.min.js') }}";
        script.async = true;
        document.body.appendChild(script);
    }
}
</script>
@endpush

方式二:通过组件mounted钩子派发事件加载

  1. 在Livewire组件类中添加mounted方法,派发前端事件:
<?php

namespace App\Http\Livewire;

use Livewire\Component;

class YourComponent extends Component
{
    public function mounted()
    {
        $this->dispatch('load-bootstrap-js');
    }

    public function render()
    {
        return view('livewire.your-component');
    }
}
  1. 在组件blade文件中监听事件,动态加载脚本:
@push('scripts')
<script>
document.addEventListener('livewire:initialized', () => {
    Livewire.on('load-bootstrap-js', () => {
        const existingScript = document.querySelector('script[src="{{ url('/assets/js/bootstrap.bundle.min.js') }}"]');
        if (!existingScript) {
            const script = document.createElement('script');
            script.src = "{{ url('/assets/js/bootstrap.bundle.min.js') }}";
            script.async = true;
            document.body.appendChild(script);
        }
    });
});
</script>
@endpush

额外检查:确认JS文件路径正确

可通过查看页面源代码,确认{{ url('/assets/js/bootstrap.bundle.min.js') }}生成的URL是否指向真实存在的文件,路径错误也会导致加载失败。

内容的提问来源于stack exchange,提问作者Md Sharif Uzzaman Rubel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:31:34