Jump to content

External JavaScript File

Recommended Posts


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:

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

And my JavaScript Code --> main.js:

function 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 post
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() {


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...