-1

I've started playing around with JS but I'm having some trouble calling a function from an external file.

I've tried most solutions in other questions posted here but still cannot get the function to execute.

I have the following JS File (myjs.js):

console.log("Loaded JS");

//Startup function
function setup(){
    console.log("Testing");
}

setup();

And here's the HTML which uses it:

<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="mycss.css"/>
    <script type="text/javascript" src="myjs.js"/>
  </head>

  <body>

    <script type="text/javascript"> setup(); </script>

  </body>

</html>

I've tried loading the script in the body and then calling the setup() function, and expect to see the following in the console:

Loaded JS //From loading JS
Testing   //From loading JS
Testing   //Invoking setup

Instead I only see:

Loaded JS
Testing

What exactly am I doing wrong?

Thanks.

user6635665
  • 167
  • 1
  • 12
  • The `setup();` in the body and the `setup();` that you probably have in your `myjs.js` file seem to be running at different times. Check here to consolidate your myjs.js file. http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the – ntgCleaner Mar 14 '17 at 13:52
  • @ntgCleaner — They aren't running at different times. One isn't running at all. – Quentin Mar 14 '17 at 13:54
  • @Quentin, you're right. I really just wanted to give him the link to a way to fix it. – ntgCleaner Mar 14 '17 at 13:55
  • @ntgCleaner — The link doesn't say anything that is remotely relevant to the problem. – Quentin Mar 14 '17 at 13:56
  • @Quentin, The answer to that question details multiple ways to fire events when a page loads. – ntgCleaner Mar 14 '17 at 13:57
  • @ntgCleaner — None of which deals with the problem … which is that the end tag for the script element is missing. – Quentin Mar 14 '17 at 13:58
  • @Quentin, Let's hope that's his only problem. I'll cheer for your answer as well. – ntgCleaner Mar 14 '17 at 13:58

1 Answers1

0

Use a validator.

The end tag for a script element (</script>) is mandatory.

Since you omitted it from your first script element, everything following it (including the start tag for your second script tag) up until </script> is inside that script.

Since the script has a src, the body is ignored.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205