Connecting JavaScript to HTML not working

Question:
Ok so i’m trying to connect the ‘script.js’ file to the HTML (External JS) but from some reason it’s not working, however, when I use the <script></script> tags in the HTML file it works without chnaging the code
Repl link:
https://replit.com/@JohnnySuriano/Cycle-Clicker#index.html

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="script.js"></script>
  <title>Cycle Clicker</title>
</head>

<body>
  <p>Score: <span id='score'>0</span></p>
  <img src="images/cycle.png" height="256px" width="256px">
</body>

</html>

JS

let score = 0;

score = score + 1;

document.getElementById('score').innerHTML = score;

alert(score)

Files
Screenshot 2023-08-20 14.16.17

Knowing me it would probably be some stupid spelling mistake or something but thanks for any help

The alert function returns the number 1, or does the JavaScript file not run?

@JohnnySuriano The script tag should be in body, maybe?

Nothing runs in the JavaScript file at all

Thanks! I find it odd though because in all my other projects the script tag in the head works fine

1 Like

Apparently not, removed the alert() a now it doesn’t work???

Maybe there’s an issue with it running before the page loads? Perhaps tie it to the DOMLoaded event or something.

3 Likes

Your script is running before the rest of the page has loaded, so it can’t see the score element. To fix this, add the defer attribute to your script tag:

<head>
  ...
  <script src="script.js" defer></script>
  ...
</head>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer

6 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.