Javascript работает только при встраивании в html [дубликат]

У меня есть функция JavaScript для переключения видимости пароля. Функция работает правильно, когда JS встроен прямо в html с тегами <script>, но не работает, когда я запускаю его из отдельного JS файла в папке static/hello/_js

Консоль регистрирует ошибку:

login.js:3 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

HTML:

{% extends "hello/layout.html" %}

{% block style %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />
{% endblock %}

{% block scripts %}
{% load static %}
<script src="{% static 'hello\_js\login.js' %}"></script>
{% endblock %}


{% block content %}
<hr>
<div class="form">
    <form>
        <h2 style="text-align:center">Login</h2>
        <div>
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" class="field">
        </div>
        <br>
        <div>
            <label for="user-pw">Password:</label>
            <input type="password" id="user-pw" name="user-pw" class="password">
            <i id="visibilityBtn"><span id="icon" class="material-symbols-outlined">visibility_off</span></i>
        </div>
        <button style="text-align: center;">login</button>
    </form>
</div>

{% endblock %}

и JavaScript:

const visibilityBtn = document.getElementById("visibilityBtn");
visibilityBtn.addEventListener("click", toggleVisibility);

function toggleVisibility() {
    const passwordInput = document.getElementById("user-pw");
    const icon = document.getElementById("icon")
   
    if (passwordInput.type === "password") {
        passwordInput.type = "text";
        icon.innerText= "visibility"
    } else {
        passwordInput.type = "password";
        icon.innerText = "visibility_off"
    }
}   
Вернуться на верх