External JavaScript

Hello, I'm currently working on a HTML file where I link an external JavaScript file so that I don't have to keep writing out large functions within the HTML itself. I'm using the <script> tags but when I run the HTML it doesn't seem to be executing the function from the JavaScript file, here is a simplified example to demonstrate what I mean:

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<title>Test</title>
</head>

<body>


<h1>This is a test</h1>

// Importing JavaScript file (I've checked that the file path is correct)
<script type="text/javascript" src="LargeFunctions.js">

// Attempting to use a JavaScript function created in the imported file
externalTest();

</script>


</body>

</html>




JavaScript

1
2
3
4
function externalTest()
{
alert("If this message is displayed then the javascript file has been successfully linked to the html");
}



As you can see the externalTest() function should display alert text as soon as I load the web page, but instead it just does nothing. If I write the exact same function in embedded JavaScript in the HTML file it works like you'd expect (displays dialog once you load the page). If anyone could help me out that would be great. Thanks in advance.
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="LargeFunctions.js"></script>    
    </head>
    <body onload="externalTest();">
        <h1>This is a test</h1>
    </body>
</html>
Last edited on
Thanks, this worked for me. It's probably worth mentioning that I had another pair of <script> tags for the embedded JavaScript, so I put the <script> tags for importing the external JavaScript above the the <script> tags for the embedded JavaScript and it allowed me to use the external JavaScript functions in the HTML file.
Topic archived. No new replies allowed.