Jump to content

External JavaScript File


noobdesigner

Recommended Posts

Hello,

first of all, sorry for the extremly nooby quastion and my not so good English, but this makes me insane.

My HTML Code --> index.html:

<html>
<head>
    <script src="main.js"></script>
</head>
<body>
    <input id="btn" type="button" value="Button">
</body>
</html>

And my JavaScript Code --> main.js:

function test()
{
    alert("Test");
}
btn.addEventListener ("click", test);

It is written everywhere, that the <script src="xyz"></script> should be written as high as possible, respectivly within the <head> Tags.
But the code above do not work --> Why?? 

The code works only if my script is written/loaded after the <input> Tag. Is this works as desinged? Should the script import really written at the end of the HTML page?

Thanks in advance.

 

Edited by noobdesigner
Link to comment
Share on other sites

The page loads in order from top to bottom and the Javascript runs as soon as it can even if the rest of the page has not loaded yet.

One way to solve it is to always put scripts before the closing </body> tag.

Another way is to have the code wait for the page to load before assigning the event listener. This can be done with the DOMContentLoaded event:

window.addEventListener("DOMContentLoaded", attachEvents);

function attachEvents() {
  var p = document.getElementById("btn");
  p.addEventListener ("click", test);
}

function test() {
  alert("Test");
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...