简体   繁体   中英

Javascript: Using External Scripts

I am trying to import a simple script into an HTML doc. It won't work and I have no idea what I am doing wrong.

Name of external script--> (function.js)

window.onload = myFunction;

       function myFunction() 
       {
             document.getElementById("HERE").innerHTML = "message";
       }

name of HTML doc--> (attributes.html)

<!DOCTYPEhtml>

    <html>
    <head>

         <title> This is an example of using an external script</title> 
            <script type ="text/javascript" src= "function.js"></script>
    </head>
    <body>

          <h1 id="HERE"> 
          </h1>

    </body>
    </html>

I think that the body on load event fires too early, before js file go running. Try to use "document.body.onload" at least of "window.onload". Try to use "document.attachEvent":

document.attachEvent(document.body, "load", myFunction)
<html>
<head>

     <title> This is an example of using an external script</title> 
        <script type ="text/javascript" src= "function.js"></script>
</head>
<body>

      <h1 id="HERE"> 
      </h1>

     <script>myFunction() </script>
</body>
</html>

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