简体   繁体   中英

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!

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.

type属性的值应为text/javascript ,如下所示:

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

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"; }; 

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM