Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

448
Vistas
How to use seperate js files in Laravel Blade

I'm trying to have different JS files for each Blade View in Laravel to help keep the project structure clean.

My problem is, when I try to access a function from that JS file in a Blade view, the console returns an error of:

Uncaught ReferenceError: myFunc is not defined at HTMLButtonElement.onclick

But the file is there and it logs the console message from that js file.

Here are my files and structure:

resources/js/index.js

console.log("Hello from index js");

function myFunc() {
    console.log("Hello");
}

resources/views/layout/master.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
    </head>
    <body>
       @yield('content')
       {{-- @yield('js') --}}
       @stack('js')
    </body>
</html>

resources/views/index.blade.php

@extends('layout.master')
@section('content')
    <h1>Works</h1>
    <button onclick="myFunc()">Click</button>
@endsection
@push('js')
<script src="{{ asset('js/index.js')}}"></script>
@endpush

webpackmix.mix.js

const mix = require("laravel-mix");

mix.js("resources/js/app.js", "public/js").postCss(
    "resources/css/app.css",
    "public/css",
    [
        //
    ]
);

mix.js("resources/js/index.js", "public/js");
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your function defined in script that loaded after main body content, but you trying to access this function in main body content.

  • Try to switch to selector for the button in JS file
  • Or load script sync before body (BAD: defers content render)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda