javascriptdeferred

Why isn't the defer working in this case on my laravel project?


I'm using a layout template to yield scripts and content as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title', 'The Gourmet')</title>
    <link rel="stylesheet" href="{{ asset('css/style.css') }}">
    @yield('scripts')
</head>
<body>
    @include('layout.employee.header')
    @yield('content')
    @include('layout.footer')
</body>
</html>

Then in my blade.php I have the following:

@extends('components.layout')

@section('title')
    {{ env('APP_NAME') . ' - Reserve' }}
@endsection

@section('scripts')
<script defer>
    let dateInput = document.getElementById('reservationDate');
    alert(dateInput.value);
</script>
@endsection

@section('content')
     <input type="date" name="reservationDate" id="reservationDate" min="{{ date('Y-m-d') }}" value="{{ date('Y-m-d') }}">
@endsection

The input has a value, and my script works if I place it underneath my input. But when I add my script through sections, it loads the script before my html and gives an "undefined" error because my input hasn't loaded yet even though I'm using the 'defer' attribute ..

So I'm just trying to get my script to work after page load using the sections to place it in the head of my html. But it keeps loading if before it renders my html, even using the defer attribute.


Solution

  • <script>
        document.addEventListener('DOMContentLoaded', function() {
            let dateInput = document.getElementById('reservationDate');
            alert(dateInput.value);
        });
    </script>