Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Adyllium's avatar

JS does not loading 'till i refresh a page

Hi everyone,

I need help to find a solution for an issue :

I'm currently developping an App on Laravel 8 and JS is not loading on every pages untill i refresh.

I've already searched for a solution everywhere i can but for now i'm really blocked.

Some informations about the issue :

  • Clicking on every links firing the issue but when i'm reaching a page derectly by the navigator bar, it's ok.
  • On every pages, when i'm refreshing one time ( F5 ), all is working correctly.
  • Css is correctly loaded everytime.
  • I've already re-worked the entire blade layout and checked all @includes and @yield calls

Really needing help. Tell me if you need some screen or page code.

Do you have any idea how to find where the error comes from?

Laravel 8.75 Jetstream 2.6 Livewire 2.5

0 likes
18 replies
sr57's avatar

Have you look at the source code in your browser to confirm js is not present?

Comment out maximum of code that confirm your pb and find by this way your pb or post the code after having delete all your commented code.

Adyllium's avatar

@sr57 Yes, i've already checked that. JS file are correctly called and imported but not executed ( sorry if i used the wrong word to describe my problem, i'm french and i do not speak English as much as i would ).

My brower logs detect 16 errors and 16 warnings, all about alpine JS but only the first time i load a page :

defer.js:1666 Uncaught TypeError: Cannot read properties of undefined (reading 'find') at eval (eval at safeAsyncFunction (defer.js:1710), :4:31) at defer.js:1728 at tryCatch (defer.js:1655) at evaluate (defer.js:1673) at defer.js:3127 at Function. (defer.js:2376) at flushHandlers (defer.js:1785) at stopDeferring (defer.js:1790) at deferHandlingDirectives (defer.js:1793) at initTree (defer.js:1991)

When i'm refreshing, all errors disappear and all work fine.

NOTICE : I'm using Materialize CSS with laravel, and the materialize JS, custom JS and all other libraries JS based does not working.

Here my app.blade.php

@include('layouts.metas') @guest

Permission denied !

@else @include('layouts.toast') @include('layouts.header') @include('layouts.breadcrumb') @hasSection('enable_tabs') @include('layouts.tabs') @else @hasSection('content') @yield('content') @else Aucun contenu @endif @endif @include('layouts.footer') @hasSection('footer_scripts') @yield('footer_scripts') @endif @stack('scripts') @endguest

And here my meta.blade.php

{{ config('app.name', 'Laravel') }} - @yield('page_title', __('Dashboard')) @hasSection('custom-style-before') @yield('custom-style-before') @endif @stack('custom-style-before') @hasSection('custom-style-after') @yield('custom-style-after') @endif

huh, can you tell me how to use laracast markdown too ? :D it seems my code not recognized by parser XD

sr57's avatar

Comment out maximum of code that confirm your pb and find by this way your pb or post the code after having delete all your commented code.

Commentez le maximum de code qui confirme votre pb et trouvez par ce moyen votre pb ou postez le code après avoir supprimé tout votre code commenté.

Merci de suivre cette procédure et formatez correctement vos posts.

Adyllium's avatar

@sr57 it doesn't work, the parser don't recognizing my codes and just run it :/ (as you can see below) even if i deleted all commented code.

well... i've already tried to comment some code to find my pb but no success :/ and its been 16 years gone that i'm developper, never see that kind of problem before. i really searched for a solution for days and weeks before asking here, i really need help. So sorry, i can't post my code properly with that parser :/

@include('layouts.metas') @guest

Permission denied !

@else @include('layouts.toast') @include('layouts.header') @include('layouts.breadcrumb') @hasSection('enable_tabs') @include('layouts.tabs') @else @hasSection('content') @yield('content') @else Aucun contenu @endif @endif @include('layouts.footer') @hasSection('footer_scripts') @yield('footer_scripts') @endif @stack('scripts') @endguest
sr57's avatar

You are in a blade page, isn'it? How do you comment out some code ?

Adyllium's avatar

@sr57 it depends. for html comment ( explain comment or TODO ) i comment my code with html comment tag.

For blade comment, like that {{-- something to say --}}

i'm developping with Visual Studio Code

sr57's avatar

@Adyllium

OK for comment method.

To format your code here, just put your code between 3 `

like this

nothing to do with the tool you use

Adyllium's avatar

@sr57 well, ok :)

so here my app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    @include('layouts.metas')
</head>

<body>
    @guest
        <h1>Permission denied !</h1>
    @else
        <div id="app">
            @include('layouts.toast')
            <header>
                @include('layouts.header')
                @include('layouts.breadcrumb')
            </header>
            <main id="app-content">
                <div id="app-container" class="container">

                    @hasSection('enable_tabs')
                        @include('layouts.tabs')
                    @else
                        @hasSection('content')
                            @yield('content')
                        @else
                            Aucun contenu
                        @endif
                    @endif
                </div>
            </main>
            @include('layouts.footer')
        </div>
        @hasSection('footer_scripts')
            @yield('footer_scripts')
        @endif
        @stack('scripts')
    @endguest
</body>

</html>

and metas.blade.php

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">

<title>{{ config('app.name', 'Laravel') }} - @yield('page_title', __('Dashboard'))</title>

<link rel="icon" href="{{ asset('favicon.png') }}" type="image/x-icon" />
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

@stack('custom-style-before')
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
@hasSection('custom-style-after')
    @yield('custom-style-after')
@endif

<script src="{{ mix('js/app.js') }}"></script>
<script src="{{ mix('js/custom.js') }}"></script>
<script src="{{ mix('js/defer.js') }}" defer></script>

Ahhhhhh yeah, it's really better, thanks for the tips ;) Tell meif your need other of my codes. the difficulty of this issue is that the code is working properly... except the first time you arrive on a page by following a link under the app. Remind, if i'm writing the URL directly in the brower bar, the JS is running correctly without refreshing.

sr57's avatar

:-)

So try to simplify your code till you understand it having a look to the source code of the html page generated. For instance begin by removing @guest ... @else @endguest

When you have got a simple code, adda simple script "alert('I am here')" and have it work, then you shpuld understand your main script.

Adyllium's avatar

@sr57 gest directive deleted, still doesn't work. But i found something :

it appear that JS are running with one page late. I mean : On some pages i use ajax formularies. So i'm generating csrf tokens for each of them. To control that for testing, i wrote into the js function that code

    $(".ajax-form").each(function () {
        /*TODO To delete*/console.log('loadCard called : add csrf token ' + $("input[name=_token]", this).val());
        $.ajaxSetup({
            headers: {
                "X-CSRF-TOKEN": $("input[name=_token]", this).val(),
            },
        });
        $(this).on("submit", function (event) {
            event.preventDefault();
            var route = $(this).attr("action");
            var _method = $(this).attr("method");

            $.ajax({
                url: route,
                type: _method,
                data: $(this).serialize(),
                success: function (data) {
                    printMsg(data);
                },
            });
        });
    });

The console.log task ran properly after reload... well, i thought. in fact, i tried to pass from one page with an ajax form to the dashboard and, Oh! ==> console log displayed the message of generating token Oo?! ( the page that doesn't work without refreshing).

sr57's avatar

-1- guest directive deleted

-2- On some pageS

-1- SIMPLIFY to understand (guest directive was only the first example)

-2- understand only on ONE page

Adyllium's avatar

@sr57 Sorry if you don't understood.

  1. yes, no more @gest directive in my app.
  2. Yes, for example, i've added a formulary in profile manager ( jetstream ). That form is attached to an Ajax script.

see code below :

 <form method="POST" action="{{ $contact->id ? route('contact.update', $contact->id) : route('contact.store') }}"
        class="ajax-form">
        @csrf
        <input name="_method" type="hidden" value="PUT">

		[a lot of inputs]

<div class="row">
            <div class="col s6 offset-s3 center-align">
                <button type="submit" class="btn btn-primary">
                    @lang('Save')
                </button>
            </div>
        </div>
    </form>

The jquery code (in custom.js) :

    $(".ajax-form").each(function () {
        /*TODO To delete*/console.log('loadCard called : add csrf token ' + $("input[name=_token]", this).val());
        $.ajaxSetup({
            headers: {
                "X-CSRF-TOKEN": $("input[name=_token]", this).val(),
            },
        });
        $(this).on("submit", function (event) {
            event.preventDefault();
            var route = $(this).attr("action");
            var _method = $(this).attr("method");

            $.ajax({
                url: route,
                type: _method,
                data: $(this).serialize(),
                success: function (data) {
                    printMsg(data);
                },
            });
        });
    });

So, each time i'm loading this page (/user/profile?{profile_id}) i should get a message in console like

loadCard called : add csrf token c6NkS8JCHn*****************xSAv

Consider this :

====> I'm going on 127.0.0.1/user/profile?2 |

console :

defer.js:1666 Uncaught ReferenceError: show is not defined
    at eval (eval at safeAsyncFunction (defer.js:1710), <anonymous>:3:32)
    at defer.js:1728
    at tryCatch (defer.js:1655)
    at defer.js:3166
    at reactiveEffect (defer.js:496)
    at Object.effect3 [as effect] (defer.js:471)
    at effect (defer.js:1309)
    at wrappedEffect (defer.js:1325)
    at Function.<anonymous> (defer.js:3166)
    at flushHandlers (defer.js:1785)

===> refreshing | console :

loadCard called : add csrf token c6NkS8JCHn*****************xSAv

===> refreshing again | console :

loadCard called : add csrf token c6NkS8JCHn*****************xSAv

===> going on dashboard | console :

loadCard called : add csrf token c6NkS8JCHn*****************xSAv

===> refreshing | console : [empty]

  1. Yes i already tried to simplify app.blade.php and other layouts too.

  2. no, the problem appear on each page.

sr57's avatar

javascript is present but you have an error, show function not present.

try update you app

  • composer update

  • npm install

  • npm run dev

share your composer.json , package.json if it does not work

Adyllium's avatar

@sr57 still doesn't work :/

composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "diglactic/laravel-breadcrumbs": "^7.1",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.75",
        "laravel/jetstream": "^2.6",
        "laravel/sanctum": "^2.11",
        "laravel/tinker": "^2.5",
        "larswiegers/laravel-maps": "^0.8.0",
        "livewire/livewire": "^2.5",
        "nwidart/laravel-modules": "^8.2",
        "yajra/laravel-datatables": "^1.5"
    },
    "require-dev": {
        "barryvdh/laravel-debugbar": "^3.6",
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel-lang/lang": "^10.4",
        "laravel-lang/publisher": "^12.2",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^5.10",
        "phpunit/phpunit": "^9.5.10"
    },
    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Modules\": "Modules/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

package.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "@tailwindcss/forms": "^0.4.0",
        "@tailwindcss/typography": "^0.5.0",
        "alpinejs": "^3.0.6",
        "axios": "^0.21",
        "jquery-ui": "^1.13.0",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "materialize-css": "^1.0.0",
        "postcss": "^8.1.14",
        "postcss-import": "^14.0.1",
        "resolve-url-loader": "^5.0.0",
        "sass": "^1.48.0",
        "sass-loader": "^12.1.0",
        "tailwindcss": "^3.0.0"
    },
    "dependencies": {
        "turbolinks": "^5.2.0"
    }
}
sr57's avatar

You said you use jetstream and don't have the package inertiajs/inertia-laravel

Strange and not not normal

try "composer require inertiajs/inertia-laravel" (and then npm run dev)

don't know if it'll solve your pb since jetstream is a startup kit, you cannot use it on an existing project.

Adyllium's avatar

@sr57 Yes, i followed the doc to install. That's my second time using this framework ( laravel i mean ) So i'm pretty lost on some concepts XD. I'll try tomorow to install this package but i have to make a new branch before... so, tomorow :D

Adyllium's avatar

@sr57 I've quickly read the doc. I'm not sure this package will fix my issue, assuming that is something whose don't let JS being loaded. And i'm using jetstream only for the profile managment, nowhere else.

Adyllium's avatar
Adyllium
OP
Best Answer
Level 1

Finally i found the solution.

By follow the Turbolink Doc, the code below are mentionned to initiate Turbolink through laravel Mix

var Turbolinks = require("turbolinks")
Turbolinks.start()

That was my matter was that Turbolink were initiate twice :)

Good code =>

var Turbolinks = require("turbolinks");
/*nothing else*/

That's all !!!

thank for your help @sr57 without you I would never have found !

Please or to participate in this conversation.