SemperCallide
SemperCallide

Reputation: 2080

HTML is not reading external Javascript file

I am trying to write a very simple HTML page that displays a message generated by a JS file. I am somewhat new to HTML / JS and I am certain there is something pretty simple I am missing, but I cannot for the life of me get the page to read the script. When I load the page, it is completely BLANK without any errors in the inspector.

This is the project folder structure:

-Project (folder)
--templates (folder)
----home.html
--src (folder)
----home.js
--styles (folder)
----home.css

Also, I'm pretty sure that my HTML page SEES the script, because when I remove or rename the script, I get an error in the browser's inspector telling me that it cannot find the script. So it SEES the script, it just is not running it for some reason.

Here is the code...

home.html:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="../styles/home.css"></link>
        <script type="type/javascript" src="../src/home.js"></script>
    </head>
    <body>
        <div id="bodytext"></div>
    </body>
</html>

home.js:

(function() {
    console.log("I AM READING THE SCRIPT");
    document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
})();

Could some generous soul out there please clue me in to what extremely simple mistake I'm making?

Thank You!

Upvotes: 0

Views: 17083

Answers (4)

ask4jubad
ask4jubad

Reputation: 33

What worked for me was adding charset="utf-8" to my css link as well as my javascript script (for me, both did not work). Example:

<link rel="stylesheet" type="text/css" href="css/main.css" charset="utf-8"></link>

<script src="javascript/script.js" charset="utf-8"></script>

Upvotes: 0

PPK
PPK

Reputation: 11

Value for type attribute should be text/javascript as follows

enter code here

ALong with this you will have to change your java script code as follows, so that script gets executed only when page is completely loaded & document object is availabe.

window.onload = function() {
     console.log("I AM READING THE SCRIPT");
    document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
};

Upvotes: 0

Hatchet
Hatchet

Reputation: 5428

Your script is running before the DOM is completely done loading. If you put your <script> tag right before your closing body tag (</body>), it will run after the DOM is loaded, and you will be able to traverse the DOM like normal.

Upvotes: 2

leo.fcx
leo.fcx

Reputation: 6467

Value for type attribute should be text/javascript as follows:

<script type="text/javascript" src="../src/home.js"></script>

Upvotes: 3

Related Questions