Code not working is js seprate file but it works when i put it in a <script>

so as the title says, i want to create a loader but the script works when i put it in the html file but i doesn’t when i put it in my sperate js file

here’s the script

var loader = document.getElementById("ld");
    window.addEventListener("load", function()
    {
      loader.style.display = "none";
    })

and here’s the html

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="Bilal el Badaoui">
<meta name="description" content="The best clothes for the best price">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>S&B Clothes</title>
    <link rel="icon" type="image/x-icon" href="logo/icons8-needle-96.png">
</head>

<body id="body">

<div class="loader" id="ld"></div>

</body>

>Solution :

This block is the problem. Change this block:

var loader = document.getElementById("ld");
    window.addEventListener("load", function()
    {
      loader.style.display = "none";
    })

to:

window.addEventListener("load", function()
{
  var loader = document.getElementById("ld");
  loader.style.display = "none";
})

Why?
You include your js script in the head of your dom. Then you have to wait if the entire dom is loaded. Because your script will start to select a element which is not loaded. For this reason you have to put your code inside the load event.

Leave a Reply