简体   繁体   中英

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.

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>

Check the JavaScript error console.

Your code runs before the document is rendered so the node testElemet doesn't exist. Either move your script-include down as the last element in the body or wrap your code in a load/ready event.

function on_document_ready(callback) {
    if (document.readyState === "complete") {
        callback();
    } else {
        document.addEventListener("DOMContentLoaded", callback);
    }
}

on_document_ready(function () {
    var paragraph = document.getElementById("testElemet");

    paragraph.innerHTML = "Test Message";
});

This should work fine:

 var paragraph = document.getElementById("testElement"); paragraph.innerHTML = "Test Message"; 
 <!DOCTYPE html> <html> <head> </head> <body> <p id="testElement">Html text</p> <script type="text/javascript" src="/js/js.js"></script> </body> </html> 

Please make sure that <script type="text/javascript" src="/js/js.js"></script> is placed just before </body> .

Try this

 var doSomething = function() { var paragraph = document.getElementById("testElement"); paragraph.innerHTML = "Test Message"; } 
 <!DOCTYPE html> <html> <head> <script type="text/javascript" src="js.js"></script> </head> <body onload = "doSomething();"> <p id="testElement"> Html text</p> </body> </html> 

Try saving both the files in the same folder.

Make use of your browsers developer console, to determine whether any errors have occurred.

Regarding 'onload', you can have a look at this link .

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