document.addEventListener('load', () => {
console.log('hi')}
)
h1, h2{
color:white;
text-align: center;
font-weight: 300;
}
body{
background-color: rgb(24, 24, 24);
overflow-x :hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel = "stylesheet" href = "style.css">
<script src = "script.js"></script>
<title>Test</title>
</head>
<body>
<h1 style="font-size: 50px;" id = "hi">Hi</h1>
</body>
</html>
(By the way, this isn't the full code. It is just some placeholder stuff.)
As you can see from the snippet, the 'hi' doesn't appear in the console.log. Any ideas why?
CodePudding user response:
There is no load
event fired on the document
object.
You could use a DOMContentLoaded
event or listen for a load event on the window
object.
Note that they fire at different times, so make sure you read the documentation to understand which is right for you.
You might also wish to remove the event listener entirely and use a defer
attribute to delay script execution instead.
This would delay script execution until after the DOM was ready (which is probably why you are trying to use an event handler here) while also allowing the script to download in parallel with the HTML being parsed (which is a slight performance enhancement).
CodePudding user response:
You are listening to the wrong event. E.g.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
Read more here: https://developer.mozilla.org/de/docs/Web/API/Window/DOMContentLoaded_event
CodePudding user response:
Maybe you have Javascript disabled in your browser. Check that out by going to the Dev tools and press Ctrl Shift P and search for "enable javascript".