pj-infest pj-infest - 5 months ago 10
HTML Question

Problems with including external JS file to HTML

I've read many tutorials and tried them, but they don't work.
Just for example I wrote this simple code:

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<p id="testElement"> Html text</p>

<script>
var paragraph = document.getElementById("testElement");
paragraph.innerHTML = "Test Message";
</script>

</body>
</html>


I get
Test Message
text in my page.

Then I put my JS code to an external file: '
/js/js.js
'

var paragraph = document.getElementById("testElement");

paragraph.innerHTML = "Test Message";


And modify the HTML file to:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/js/js.js"></script>
</head>
<body>

<p id="testElement"> Html text</p>

</body>
</html>


When I open the HTML file in a browser, I only get
Html text
. My JS does not work. Please explain what I am doing wrong.

Answer

Your problem is that javascript linked in head is executed before the body is loaded, so you can just put the script at the end of the body like this:

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
        <p id="testElement"> Html text</p>
        <script type="text/javascript" src="js/js.js"></script>
    </body>
</html>
Comments