Skip to content Skip to sidebar Skip to footer

Javascript Not Working In External File

I'm trying some JS basics for a little test and have encountered with a problem when trying to put the Javascript code outside of the HTML one. The HTML:

Solution 1:

Put the <script> tag with which you import your JavaScript at the very end of the <body> instead of in the <head>.

Imported scripts are evaluated as soon as the browser gets them, synchronously. If you put a script in the <head> and it tries to find DOM elements, they won't exist because the body of the document hasn't been parsed yet. By putting the script at the end, you avoid that problem.

edit — in your jsfiddle, the code works because that site by default wraps your JavaScript code up inside a function that's set up as a "load" handler for the page. It won't run until after the page has loaded. That's another option for you too, but you'll have to structure the code that way yourself.


Post a Comment for "Javascript Not Working In External File"