javascripthtmldom

Implement JS in HTML


It should be easy, but as easy as it should be I can't solve the problem.

If I'm typing the following HTML and JS code into an online editor, everything works fine but if I'm typing this into my (offline) editor it won't work. Here's the online code: http://jsbin.com/kenurunahu/1/edit?html,js,output)

I bet it has something to do with the loading order and how the files are linked.

Thats how my (lokal) HTML-file looks like (where the files are linked):

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" content="Index.css">
  <script src="Script.js"></script>
</head>

<body>
  <p id="demo">
    something
  </p>
</body>

</html>

Many Thanks for Help!

[Update] Firefox and Chrome display the JS file. Sometimes I get an error message that says 'innerHTML is null', but if I write the same code into the console everything works fine.


Solution

  • you have the error when the js script is loaded before the html dom is fully loaded by the browser. A simple solution for your testing is to place the script include at the end of your html page, like this :

    <!DOCTYPE html>
    <html>
    
    <head>
      <link rel="stylesheet" content="Index.css">
    </head>
    
    <body>
      <p id="demo">
        something
      </p>
      <script src="Script.js"></script>
    </body>
    
    </html>
    

    A better solution is to run your script only when the dom is fully loaded. For example with the body onload event :

    <body onload="yourFunc()"> 
    

    Or event better by using only js code, for example with jquery ready function or by writing a simple custom handler that should work on all major browsers :

    document.addEventListener("DOMContentLoaded", function(event) { 
      //call your func here
    });
    

    Hope that helps.